SQL加入重复结果

时间:2013-04-28 19:53:43

标签: mysql sql join concat

我一直在学习SQL,比平常学到更高级的程度,而且我对这一点有点困惑。

查询是从一个用户输入的原点获得航空公司飞往(目的地)的所有机场。

SELECT DISTINCT a.airline_name, GROUP_CONCAT(ap.city) AS groupedDestinations
            FROM routes AS r
            LEFT JOIN airlines AS a
                ON r.airline = a.airline_iata
            LEFT JOIN airports AS ap
                ON r.destination = ap.airport_iata
            WHERE r.origin = ? AND a.active="Y" AND r.codeshare != "Y"
            GROUP BY a.airline_name ASC

结果应为:

Airline Name | city1, city2

取而代之的是:

Airline Name | city1, city2, city1, city2

我花了几个小时来达到这一点,所以我很感激任何建议,滥用或答案:)

谢谢。

1 个答案:

答案 0 :(得分:3)

使用group by时,distinct子句中的 <{em}}需要select

您遇到的问题是航空公司可能有多条通往某个城市的路线。这导致城市重复。默认情况下,group_concat()不会删除这些重复项。要解决此问题,您需要distinct中的group_concat

SELECT a.airline_name, GROUP_CONCAT(distinct ap.city) AS groupedDestinations
            FROM routes AS r
            LEFT JOIN airlines AS a
                ON r.airline = a.airline_iata
            LEFT JOIN airports AS ap
                ON r.destination = ap.airport_iata
            WHERE r.origin = ? AND a.active="Y" AND r.codeshare != "Y"
            GROUP BY a.airline_name ASC;