2013-11-01 58 views
3

給定一個包含幾何數據和使用ST_INTERESECTS()的多邊形表,如何返回相交的多邊形,同時防止我們的結果變得多餘?PostgreSQL如何返回元組{a,b}但不是元組{b,a}?

需要明確的是,如果我們返回多邊形A相交多邊形B則是多餘的也返回行多邊形B相交多邊形A.

實施例:

SELECT table1.name, table2.name 
FROM tl AS table1, tl AS table2 
WHERE table1.name <> table2.name // prevent returning A intersects A 
AND ST_INTERSECTS(table1.coords, table2.coords) 
ORDER BY table1.name asc; 

返回

 
hi hello 
peanut butter 
hello hi 
butter peanut 

我想要

 
hi hello 
peanut butter 

回答

4

你只需決定你總是首先提出的較小值,並且使用<而不只是<>

SELECT table1.name, table2.name 
FROM tl AS table1, tl AS table2 
WHERE table1.name < table2.name -- The aforementioned assumption 
AND ST_INTERSECTS(table1.coords, table2.coords) 
ORDER BY table1.name asc; 
+2

+1這標準的方式。我們假設'name'是PK – leonbloy

+0

那麼,這比預期容易得多。另外,leonbloy,謝謝你提到我們假設'name'是PK。它不是,但我輕鬆地調整了查詢​​使用PK。我會盡可能接受。 – TylerN

1

另一種選擇的是應用DISTINCT的結果:

SELECT DISTINCT least(table1.name, table2.name) as name1, 
       greatest(table1.name, table2.name) as name2 
FROM tl AS table1, tl AS table2 
WHERE table1.name <> table2.name -- prevent returning A intersects A 
AND ST_INTERSECTS(table1.coords, table2.coords) 
ORDER BY table1.name asc; 
相關問題