2013-11-29 119 views
0

我有一個主表爲「master_tbl」,它具有以下字段:多表連接查詢

m_id(PK) 
m_name 

兩個從表可以是:

Slave-1 : 
--------- 
sl1_id PK 
sl1_name 
sl_m_id FK 

Slave-2 : 
--------- 
sl2_id PK 
sl2_name 
sl2_m_id FK 

我需要輸出爲像一個查詢匹配記錄的詳細信息應顯示如下:

m_id  m_name sl1_name(or sl2_name) 

最後顯示字段d取slave1Slave2表中匹配記錄的名稱。

+0

你嘗試過什麼?,分享您的查詢。 –

回答

0
SELECT m_id, m_name, sl1_name as `sl1_name(or sl2_name)` FROM slave_1 S1 
     INNER JOIN master_tbl M ON S1.sl1_m_id = M.m_id 
UNION 
SELECT m_id, m_name, sl2_name as `sl1_name(or sl2_name)` FROM slave_2 S2 
     INNER JOIN master_tbl M ON S2.sl2_m_id = M.m_id 
1

內部聯接查詢中使用

SELECT mt.name, s1.sl1_name, s2.sl2_name FROM master_tbl as mt 
INNER JOIN Slave-1 as s1 ON s1.sl_m_id = mt.m_id 
INNER JOIN Slave-2 as s2 ON s2.sl2_m_id = mt.m_id