【问题标题】:SQL Join Duplicate ResultsSQL 连接重复结果
【发布时间】:2013-04-22 10:34:07
【问题描述】:

我学习 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

我花了几个小时才达到这一点,所以如果有任何建议、滥用或回答,我将不胜感激:)

谢谢。

【问题讨论】:

    标签: mysql sql join concat


    【解决方案1】:

    当使用group by时,您确实select 子句中需要distinct

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

    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;
    

    【讨论】:

    • -_- 我要去睡觉了....非常非常感谢您,这非常有帮助。希望它可以帮助处于相同情况的其他人。
    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2023-04-02
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多