1

以下可能吗?

我有 2 张桌子,例如:

地点:

Location_key | Location     | Site_key

           1 | First Floor  | 100
           2 | Second Floor | 100
           3 | Third Floor  | 100
           4 | Fourth Floor | 200
           5 | Fifth Floor  | 200

子位置:

Sub_Location_key | Sub_Location | Location_key

               1 | Room A       | 1
               2 | Room B       | 2
               3 | Room C       | 3
               4 | Room D       | 1
               5 | Room E       | 2

我想获取每个位置内的所有子位置。因此,例如,如果我获得站点 100,我需要返回如下内容:

First Floor
----------
Room A
Room D

Second Floor
----------
Room B
Room E
4

3 回答 3

1
select l.Location, group_concat(Sub_Location)
from Location l
left outer join Sub_Location sl on l.Location_key = sl.Location_key
where l.Site_key = 100
group by l.Location 

编辑

select l.Location, 
       group_concat(Sub_Location) as sublocations, 
       group_concat(a.name) as assets
from Location l
left outer join Sub_Location sl on l.Location_key = sl.Location_key
left outer join assets a on sl.sub_location_key = a.sub_location_key
where l.Site_key = 100
group by l.Location 
于 2012-07-20T09:36:25.247 回答
0

这应该是接近...

SELECT `Location`, `Sub_Location`
 FROM `Location` LEFT JOIN  `Sub_Location` 
 ON `Location_key`
GROUP BY `Location`

而且您应该阅读一些有关命名约定的信息,例如,您似乎对使用哪种情况非常了解。

于 2012-07-20T09:36:46.077 回答
0

根据您的问题,我认为没有必要使用左连接,因此以下自然连接版本可能更合适:
SELECT l.Location, group_concat(Sub_Location) FROM Location l, Sub_Location sl WHERE l.Location_key = sl .Location_key ADN l.Site_key = 100 GROUP BY l.Location

于 2012-07-20T10:11:09.243 回答