我有mysql表
region_id | name | parent_id
1 | Österreich | 0
3 | Deutschland | 0
4 | Bayern | 3
5 | Bad Griesbach| 4
6 | Nordrhein-Westfalen| 3
7 | Île-de-France | 7
....
我写了查询
SELECT
h.hotel_id,
h.hotel_name,
t1.region_id,
t1.name AS name1,
t2.region_id,
t2.name AS name2,
t3.region_id,
t3.name AS name3
FROM
hotel_service.hotel h
LEFT JOIN region_service.region t1 ON t1.region_id = h.region_id
LEFT JOIN region_service.region t2 ON t2.region_id = t1.parent_id
LEFT JOIN region_service.region t3 ON t3.region_id = t2.parent_id
WHERE
hotel_id IN ('10640' , '10003', '10004', '10005', '10007')
结果是这样的
hotel_id hotel_name city_id name1 region_id name2 region_id name3
10003 Dorfhotel 231 Sylt 30 Schleswig 3 Deutschland
10004 Iberotel 22 Boltenhagen 21 Mecklenburg 3 Deutschland
10005 Hotel 170 Barcelona 169 Katalonien 168 Spanien
10007 Schlosshotel 175 Rügen 21 Mecklenburg 3 Deutschland
10640 Hotel Berlin 36 Berlin 3 Deutschland
但结果顺序问题,例如hotel_id 10640 - 3 Deutschland
显示在错误的列中,它应显示在最后一列,因为最后一列是country
。
如果这是唯一有问题的案例,你可以试试这个;
SELECT
h.hotel_id,
h.hotel_name,
t1.region_id,
t1.name AS name1,
case when t3.region_id is null then null else t2.region_id end,
case when t3.region_id is null then null else t2.name end,
case when t3.region_id is null then t2.region_id else t3.region_id end,
case when t3.region_id is null then t2.name else t3.name end
FROM
hotel_service.hotel h
LEFT JOIN region_service.region t1 ON t1.region_id = h.region_id
LEFT JOIN region_service.region t2 ON t2.region_id = t1.parent_id
LEFT JOIN region_service.region t3 ON t3.region_id = t2.parent_id
WHERE
hotel_id IN ('10640' , '10003', '10004', '10005', '10007')