多表连接查询

时间:2013-11-29 04:45:24

标签: mysql

我有一个主表格为“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)

最后一个显示字段应该是slave1Slave2表中匹配记录的名称。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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