2015-06-08 64 views
-1

我有三個表,其中兩個是在結構上相同mysql如何加入三表

表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不爲零的其他表之一。

+0

請告訴我們你試過SQL表達式。我們很樂意提供幫助,但我們不會做所有的工作。 – lenz

回答

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

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)