完全外连接(左连接联合右连接)MySQL多个表

时间:2015-06-12 22:58:39

标签: php mysql join union

我查看了其他相关的SO问题,但他们无法点击给我。

我有这些表格: http://i.stack.imgur.com/cEYVn.png

最后,我想组合这5个表,所以从Location(可能是loc_type(int)替换为loc_type_name),除了来自hours的loc_id之外的所有内容(因为它将在loc_id上加入),与Holiday相同,等

我已经知道如何在MySQL中复制此功能:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

我让它适用于任何两张桌子,但无法继续下去:

SELECT * FROM locations loc 
    LEFT OUTER JOIN location_types locType on locType.id = loc.loc_num 
UNION 
SELECT * FROM locations loc 
    RIGHT OUTER JOIN location_types locType on locType.id = loc.loc_num
UNION
SELECT * FROM locations loc 
    LEFT OUTER JOIN hours shours on loc.loc_num = shours.loc_id 
UNION
SELECT * FROM locations loc 
    RIGHT OUTER JOIN hours shours on loc.loc_num = shours.loc_id
UNION
SELECT * FROM locations loc 
    LEFT OUTER JOIN holiday hol on loc.loc_num = hol.loc_id 
UNION
SELECT * FROM locations loc 
    RIGHT OUTER JOIN holiday hol on loc.loc_num = hol.loc_id 

任何帮助将不胜感激!

注意:可能还有一些用于位置和其他表的附加列,所以最后,我想要一个我手工挑选所需列的列(即FROM location选择loc_id,loc_name,loc_phone)...

1 个答案:

答案 0 :(得分:0)

看看下面的查询,希望这可以帮到你!稍后您可以修改相应的

这将加入所有5个表。在这里,我将Location保留为左表,以便在触发此查询后所有位置都将显示,并且匹配的Id将与此表匹配。

SELECT * FROM location LEFT JOIN location_type ON location_type.type_id=location.loc_id
    LEFT JOIN hours ON location.loc_id=hours.loc_id 
    LEFT JOIN holiday ON holiday.loc_id=location.loc_id 
    LEFT JOIN holiday_hours ON holiday.hol_id=holiday_hours.holiday_id