I have a table like below:
| city1 | city2 | dist |
|---|---|---|
| New York | Berlin | 7900 |
| Berlin | New York | 7900 |
| Oregon | Ohio | 5700 |
| Montreal | Rio | 5700 |
| Ohio | Oregon | 5700 |
| Rio | Montreal | 5700 |
| Moscow | Tokyo | 4200 |
| Tokyo | Moscow | 4200 |
Both row 1 and row 2 are same things and the only difference is in the first one Berlin is city2 and in the second one Berlin is city1.
I want to show this kind of rows only once…
How to do it?
>Solution :
You can self LEFT JOIN and see if any matches are there
Depending on th last OR condition you can choose which cite are shown in the result set
SELECT t1.*
FROM t t1
LEFT JOIN t t2 ON t1.city1 = t2.city2 and t2.city2 = t1.city1 AND t1.dist = t2.dist
WHERE t2.city1 IS NULL
OR t1.city1 > t1.city2
| city1 | city2 | dist |
|---|---|---|
| Conce | Santiago | 500 |
| New York | Berlin | 7900 |
| Oregon | Ohio | 5700 |
| Rio | Montreal | 5700 |
| Talca | Linares | 80 |
| Tokyo | Moscow | 4200 |
SELECT 6
SELECT t1.*
FROM t t1
LEFT JOIN t t2 ON t1.city1 = t2.city2 and t2.city2 = t1.city1 AND t1.dist = t2.dist
WHERE t2.city1 IS NULL
OR t2.city1 > t2.city2
| city1 | city2 | dist |
|---|---|---|
| Berlin | New York | 7900 |
| Conce | Santiago | 500 |
| Montreal | Rio | 5700 |
| Moscow | Tokyo | 4200 |
| Ohio | Oregon | 5700 |
| Talca | Linares | 80 |
SELECT 6