在id上加入三个表

时间:2017-08-20 11:47:24

标签: sql

HeJ小鼠,

我无法完全解决这个问题...

我需要加入三张桌子。

表'房间'

name   | desccription
------ | -------------
room 1 | desccription 
room 2 | desccription 
room 3 | desccription 
room 4 | desccription 
room 5 | desccription 

表'传感器'

使用外键room_name,一个房间可以有多个传感器。

id | room_name | name 
-- | --------- | --------
1  | room 1    | sensor 1
2  | room 1    | sensor 2
3  | room 1    | sensor 3
4  | room 2    | sensor 4
5  | room 3    | sensor 5
6  | room 4    | sensor 6

表'演员'

使用外键room_name,一个房间可以有多个演员。

id | room_name | name 
-- | --------- | --------
1  | room 1    | actor 1
2  | room 2    | actor 2
3  | room 2    | actor 3
4  | room 4    | actor 4
5  | room 4    | actor 5
6  | room 4    | actor 6

结果我想要这样的东西

room.name | sensor.name | actor.name 
--------- | ----------- | -----------
room 1    | sensor 1    | NULL
room 1    | sensor 2    | NULL
room 1    | sensor 3    | NULL
room 1    | NULL        | actor 1
room 2    | sensor 4    | NULL
room 2    | NULL        | actor 2
room 2    | NULL        | actor 3
room 3    | sensor 5    | NULL
room 4    | sensor 6    | NULL
room 4    | NULL        | actor 4
room 4    | NULL        | actor 5
room 4    | NULL        | actor 6
room 5    | NULL        | NULL

我的尝试是加入这三个表并按room_name对它们进行分组,但这只会给出第一个传感器或actor(取决于NULL值)并且不会连接这些值。从长远来看,串联不会太好用,所以我更喜欢上面显示的结果。

当我尝试在表传感器和actor上使用UNION时,我无法区分传感器和演员名称。此外,我不会在结果中没有任何传感器和演员的房间。我想不可能给出sensor_name等列名。

SELECT room.name AS room_name, sensor.name AS sensor_name
FROM room INNER JOIN sensor ON room.name = sensor.room_name
UNION
SELECT room.name AS room_name, actor.name AS actor_name
FROM room INNER JOIN actor ON room.name = actor.room_name

你可以在这里找到一个具象的代表性:https://imgur.com/a/PsEQ1 (我不允许发布图片)。

你有什么建议吗?任何帮助或暗示将是欣赏! (我对SQL还不是那么精通)。

谢谢!

1 个答案:

答案 0 :(得分:0)

你做得很好,你只需要添加另一列来识别它们:

SELECT room.name AS room_name, sensor.name AS sensor_name, NULL as actor_name
FROM room 
INNER JOIN sensor
  ON room.name = sensor.room_name
UNION
SELECT room.name AS room_name, NULL as sensor_name,actor.name AS actor_name
FROM room 
INNER JOIN actor 
  ON room.name = actor.room_name

虽然您的结果集我怀疑您正在寻找LEFT JOIN而不是INNER JOIN