跳轉到內容

SPARQL/修飾符

來自華夏公益教科書,開放的書籍,為開放的世界

SELECT ... WHERE { .. } 有 4 個可選修飾符。有關介紹,請參見SELECT 章節。

五個修飾符是 GROUP BY ...HAVING ...ORDER BY ...LIMIT ...OFFSET ...

讓我們考慮一下巴赫的孩子列表,其中還列出了他們的母親

SELECT ?mother ?motherLabel ?child ?childLabel
WHERE
{
  ?child wdt:P22 wd:Q1339.# ?child has father Bach
  ?child wdt:P25 ?mother.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

試試看!

讓我們按母親對這個列表進行分組。

SELECT ?mother ?motherLabel (COUNT(?child) AS ?children) 
        (GROUP_CONCAT(DISTINCT ?childLabel; SEPARATOR=", ") AS ?names)
WHERE
{
  ?child wdt:P22 wd:Q1339.# ?child has father Bach
  ?child wdt:P25 ?mother.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". 
                          ?mother rdfs:label ?motherLabel.
                          ?child  rdfs:label ?childLabel.
                         }
}
GROUP BY ?mother ?motherLabel

試試看!

我們對 ?mother?motherLabel 兩個變數都使用 GROUP BY,因為如果省略標籤,最終會得到“錯誤的聚合”錯誤。

首先,我們添加了 (COUNT(?child) AS ?children) 來計算孩子的數量。COUNT聚合函式 MINMAXSUMAVGCOUNTSAMPLE 之一。
首先要注意的是它計算了變數 ?child。還要注意語法是 (COUNT(?var1) AS ?var2)

作為第二條資訊,我們使用 (GROUP_CONCAT(DISTINCT ?var1; SEPARATOR=", ") AS ?var2) 添加了每個母親的孩子的組合列表。

在使用 GROUP_CONCAT 和標籤時,所有標籤都應在 SERVICE 中明確定義。

HAVING 始終與 GROUP BY 結合使用

SELECT ?mother ?motherLabel (COUNT(?child) AS ?children) 
        (GROUP_CONCAT(DISTINCT ?childLabel; SEPARATOR=", ") AS ?names)
WHERE
{
  ?child wdt:P22 wd:Q1339.# ?child has father Bach
  ?child wdt:P25 ?mother.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". 
                          ?mother rdfs:label ?motherLabel.
                          ?child  rdfs:label ?childLabel.
                         }
}
GROUP BY ?mother ?motherLabel 
HAVING (COUNT(?child)>7)

試試看!

HAVING 將過濾掉不滿足指定條件的組。在這種情況下,只顯示一位母親,她有 13 個孩子。

由於 COUNT(?child) 與變數 ?children 繫結,因此 HAVING 子句也可以寫成 HAVING (?children>7)

HAVING 子句對於查詢重複項可能很有用,例如 HAVING (COUNT(?var)>1)

ORDER BY somethingsomething 對結果進行排序。something 可以是任何表示式或變數。此表示式也可以用 ASC()DESC() 包裹以指定排序順序(ascending 或 descending)。(如果未指定任何一個,則預設值為升序排序,因此 ASC(something) 等效於 something。)

SELECT ?mother ?motherLabel ?child ?childLabel
WHERE
{
  ?child wdt:P22 wd:Q1339.# ?child has father Bach
  ?child wdt:P25 ?mother.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?motherLabel) ?childLabel

試試看!

LIMIT count 將結果列表截斷為 count 個結果,其中 count 是任何自然數。例如,LIMIT 10 將查詢限制為十個結果。LIMIT 1 僅返回單個結果。

這對於獲取前 10 個結果或僅獲取 10 個隨機結果以檢視資料的外觀可能很有用。

OFFSET count 可用於跳過前幾個結果。OFFSET 100 LIMIT 10 返回第 101-110 條記錄。

參考文獻

[編輯 | 編輯原始碼]


華夏公益教科書