mysql如何加入三个表

时间:2015-06-08 08:45:33

标签: mysql mysqli

我有三张桌子,其中两张桌子结构相同

像这样的表1

-----------------------------------------------
id       title     description       image
-----------------------------------------------
1         title1   desc1             image1.png
2         title2    desc2            image2.jpg
------------------------------------------------

这样的表2

-----------------------------------------------
id       title     description       image
-----------------------------------------------
1         ttl1   des1             img1.png
2         ttl2    des2            img2.jpg
------------------------------------------------

表3就像这样

-----------------------------------------------
id       table1_id    table2_id     
-----------------------------------------------
1         0             1             
2         1             0    
------------------------------------------------

我想将table3连接到id不为零的其他表之一。

2 个答案:

答案 0 :(得分:1)

select * from table3  t3 
join table1 t1 on t1.id = t3.table2_id     
join table2 t2 on t2.id = t3.table1_id    
Where t3.table2_id <> 0 or  t3.table1_id    <> 0    

直接joinWhere

一起使用

答案 1 :(得分:0)

(select * from table3 as t3 join table1 as t1 on t1.id = t3.id and t3.table1_id != 0)
UNION
(select * from table3 as t3 join table2 as t2 on t2.id = t3.id and t3.table2_id != 0)
相关问题