SPARQL/UNION
外觀
< SPARQL
|
假設集合 A:歐盟的 28 個首都 SELECT ?city ?cityLabel
WHERE {
wd:Q458 wdt:P150 ?country. # European Union contains administrative territorial entity
?country wdt:P36 ?city. # capital
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
|
假設集合 B:歐盟的 3 個百萬人口城市。 SELECT ?city ?cityLabel
WHERE {
wd:Q458 wdt:P150 ?country. # European Union contains administrative territorial entity
?city wdt:P17 ?country. # city in a (European) country
?city wdt:P31 wd:Q1637706. # city with millions of inhabitants
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
|
A 和 B 的交集,即歐盟的大型首都,可以透過組合所有三元組輕鬆實現。這將導致 1 個城市。
SELECT ?city ?cityLabel
WHERE {
wd:Q458 wdt:P150 ?country. # European Union contains administrative territorial entity
?country wdt:P36 ?city. # capital
?city wdt:P17 ?country. # city in a (European) country
?city wdt:P31 wd:Q1637706. # city with millions of inhabitants
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
歐盟的所有首都,不包括大城市,可以透過過濾使用 FILTER NOT EXISTS { } 來實現。這將導致另外 27 個首都。
SELECT ?city ?cityLabel
WHERE {
wd:Q458 wdt:P150 ?country. # European Union contains administrative territorial entity
?country wdt:P36 ?city. # capital
?city wdt:P17 ?country. # city in a (European) country
FILTER NOT EXISTS{ ?city wdt:P31 wd:Q1637706. } # NOT a city with millions of inhabitants
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
最後,首都和大型城市的 UNION 導致 30 個城市,其中一個由 DISTINCT 去重。
SELECT DISTINCT ?city ?cityLabel
WHERE {
wd:Q458 wdt:P150 ?country. # European Union contains administrative territorial entity
{ ?country wdt:P36 ?city. } # capital
UNION
{ ?city wdt:P17 ?country. # city in a (European) country
?city wdt:P31 wd:Q1637706. # a city with millions of inhabitants
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
請注意,聯合的兩個部分都應在方括號內 { ... } UNION { ... }。
UNION 的兩個更簡單的例子是
{?a wdt:P27 wd:Q55. } UNION { ?a wdt:P27 wd:Q29999. }國籍 (P27) for 荷蘭 (Q55) 或 荷蘭王國 (Q29999).{?child wdt:P22 ?parent. } UNION {?child wdt:P25 ?parent. }父親 (P22) 或 母親 (P25).
- 最後一段程式碼可以使用屬性路徑
?child wdt:P22|wdt:P25 ?parent.簡化。
所有型別聯接的概述
| 維恩圖 | 數學 | SPARQL | |
|---|---|---|---|
| 還有 | A. B. | ||
| A. FILTER NOT EXISTS{ B. } | |||
| A. OPTIONAL{ B. } | |||
| 或 | { A. } UNION { B. } |