Forum Moderators: coopster
city_pairs (
pairid,
city1,
city2
)
The city_pairs table contain cities in pairs where a pair may occur twice
row 1: city1: 'new york', city2: 'new mexico'
row 2: city1: 'new mexico', city2: 'new york'
This is expected behaviour. Now I need to select the pairid of all pairs, but I want unique pairs. Ie, in the example above I want only the firs row. How can I do this?
I tried something like
SELECT pairid FROM city_pairs WHERE city1 in
(SELECT city1 FROM (SELECT distinct city1, city2 FROM city_pairs) as distinct_cities)
I think this query looks somewhat clumsy, and even more important, it doesn't act as expected - it returns all rows. I guess this is because ("city1", "city2") and ("city2", "city1") really are two distinct rows... Any takers?
pairidis a unique identifier).
SELECT
a.pairid,
a.city1,
a.city2
FROM city_pairs AS a
LEFT JOIN city_pairs AS b
ON (a.city1 = b.city2 AND a.city2 = b.city1)
WHERE b.city1 IS NULL OR a.pairid < b.pairid
;
Have a look at message number 11 in this thread, a bit more of an explanation:
[webmasterworld.com...]