MySQL多个表JOIN,相同的列标题

时间:2014-09-04 12:17:30

标签: mysql

我有一个问题,我不知道如何解决它。我尝试但仍然没有成功。 我有3张桌子:

id_tour    title
1          Discovery
2          Something

tour_to_country

id_tour    id_country
1          66
1          35
1          673
2          88
2          91

国家

id_country title
1          Country_1
2          Country_2
...        ...
999        Country_999

我想从巡回赛表中选择2个巡回赛,选择每个巡回赛中的所有国家并显示他们的名字。

我想从每个巡视中选择所有国家/地区,但巡视应该显示一次。

这是我尝试过的:

SELECT tour.id_tour as tour_id, tour.title as tour_title, country.title as country_title, tour.* FROM tour 
        INNER JOIN tour_to_country ON tour.id_tour = tour_to_country.id_tour 
        INNER JOIN country ON country.id_country = tour_to_country.id_country
        GROUP BY tour.id_tour

它为我提供了游览但我仍然不知道如何在同一个查询中占据所有国家/地区。

http://oi59.tinypic.com/1iby4l.jpg

1 个答案:

答案 0 :(得分:1)

GROUP_CONCAT应该为你做的伎俩。您可以指定订购和分隔符。我认为这是你想要实现的目标。

SELECT tour.id_tour as tour_id, tour.title as tour_title, GROUP_CONCAT(country.title ORDER BY country.title SEPARATOR ',') as country_title, tour.* FROM tour 
    INNER JOIN tour_to_country ON tour.id_tour = tour_to_country.id_tour 
    INNER JOIN country ON country.id_country = tour_to_country.id_country
    GROUP BY tour.id_tour