在GROUP BY中选择记​​录

时间:2012-07-20 09:32:22

标签: mysql select group-by

以下可能吗?

我有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:

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

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

这应该很接近......

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

你应该阅读一些有关命名约定的内容,例如:你似乎对使用哪种情况非常接种疫苗。

答案 2 :(得分:0)

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