# SPARQL 語法教學 作者: 朱庭宏 ## SELECT (查詢) ```sql= SELECT ?item ?itemLabel WHERE { } # ?後塞欄位名稱 若要顯示其標籤需加Label ``` ![](https://i.imgur.com/1TX8AwG.png) ## AS (代名) ```sql= SELECT ?item ?itemLabel (?itemLabel AS ?標籤) WHERE { } # AS後面仍需加變數 ``` ![](https://i.imgur.com/xtwUnSW.png) ### 注意: 若是直接寫這樣他屬性的欄位會是空值 ```sql= SELECT ?item (?itemLabel AS ?標籤) WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh".} ?item wdt:P31 wd:Q207694. } ``` ![](https://i.imgur.com/5XT9rUM.png) 應修該為下: ```sql= SELECT ?item (?itemLabel AS ?標籤) WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh". ?item rdfs:label ?itemLabel. } ?item wdt:P31 wd:Q207694. } ``` ![](https://i.imgur.com/wBbmRyu.png) ## WHERE (條件) 在```SERVICE wikibase:label```中```bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh".```子句再設定Label的語言,```?item rdfs:label ?itemLabel.```子句則是將```?itemLabel```變數參照到```?item```變數的標籤值 ```?item wdt:P31 wd:Q207694.```子句將```P31=Q207694```指定給```?item```變數 ## ORDER (排序) ```sql= SELECT ?item (?itemLabel AS ?標籤) WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh". ?item rdfs:label ?itemLabel. } ?item wdt:P31 wd:Q207694. } ORDER BY ASC(?item) # ASC為遞增,DESC為遞減 ``` ![](https://i.imgur.com/2tNFaDf.png) ## LIMIT (比數限制) ```sql= SELECT ?item (?itemLabel AS ?標籤) WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh". ?item rdfs:label ?itemLabel. } ?item wdt:P31 wd:Q207694. } ORDER BY ASC(?標籤) LIMIT 100 # 僅顯示100筆紀錄 ``` ![](https://i.imgur.com/41YzYeh.png) ## DISTINCT (去除重複) ```sql= SELECT DISTINCT ?item (?itemLabel AS ?標籤) WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],zh". ?item rdfs:label ?itemLabel. } ?item wdt:P31 wd:Q207694. } ORDER BY ASC(?標籤) LIMIT 100 ``` ## 查詢出生年月日 ![](https://i.imgur.com/OyNJCgs.png)