SQL自己加入一个表(如果可能的话)?

时间:2014-02-12 21:12:37

标签: sql database join self-join

我有一张这样的表:

room code     facility
A001              1
A001              2
A002              3
A003              1

有没有办法可以加入这个表,如下所示

room code    facility 1      facility 2
A001             1               2
A002                             3
A003             1

我需要这样,以便我可以测试哪些房间有什么设施,然后在我的html页面上,我将根据用户过滤的设施显示它们的列表

希望这是有道理的!

提前致谢

3 个答案:

答案 0 :(得分:1)

您无需加入。你可以聚合:

select roomcode,
       min(facility) as facility1,
       (case when min(facility) <> max(facility) then max(facility) end) as facility2
from t
group by roomcode;

答案 1 :(得分:0)

以下内容应该这样做(尽管它不会将3放在facility_2下,而是放在facility_1下。

select t1.room_code, 
       t1.facility as facility_1,
       t2.facility as facility_2
from the_table t1
  left join the_table t2 
         on t1.room_code = t2.room_code
        and t1.facility <> t2.facility;

这也假设永远不会有两行具有相同的room_code

如果每个房间有不明数量的设施,您可以将它们聚合成一个数组或逗号分隔的列表,然后您可以在前端处理这些列表。

像这样(对于Postgres,因为你没有提到你的DBMS)

select room_code,
       string_agg(facility,',') as facilities, -- gives a comma separated list
       array_agg(facility) as facilities_array -- gives an array of integers
from the_table
group by room_code;

答案 2 :(得分:0)

试试这个:

SELECT first.roomcode, first.facility, second.facility
FROM mytable first
LEFT JOIN mytable second on first.roomcode = second.roomcode AND first.facility != second.facility