繁体   English   中英

如何连接三张表

[英]How to join three table

我有三个表,其中两个在结构上相同

像这样的表 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 不为零的其他表之一。

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    

使用直接连接Where

(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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM