在表中添加第五个连接

时间:2018-02-08 18:52:29

标签: mysql sql join left-join inner-join

到目前为止,我已经编写了以下mysql查询,该查询正在连接4个表,如下所示:

SELECT 
T3.fault, t4.name
FROM table2 T2 
INNER JOIN (
    SELECT a.*
    FROM table1 a
    LEFT JOIN table1 b ON a.item_id = b.item_id AND a.submit_id < b.submit_id
    WHERE b.submit_id IS NULL
) T1  ON T1.item_id = T2.item_id
INNER JOIN table3 T3 ON T1.id = T3.run_id
LEFT JOIN table4 T4
ON 3.runname_id  = T4.id
order by count(*) desc;

以下是table 2的示例数据,item_idPK 示例查询:select * from table2 where item_id = '15907';

item_id  host
15907    abc.com
7303     cde.com
7304     abcd.com
7305     cdedf.com

我最近添加了一个表格table5,如下所示,item_idPK。我想在table5加入table2 item_id,并希望在我的最终查询中检索restoreid的值。

item_id  restoreId
15907       12342
7303        12342
7304        14342
7305        14342

如何在table5上实现table2item_id之间的联接?我的选择查询还应该检索T5.restoreId以及T3.fault, t4.name

2 个答案:

答案 0 :(得分:1)

<h3>

答案 1 :(得分:1)

SELECT 
T3.fault, t4.name, T5.restoreid
FROM table2 T2 
INNER JOIN (
    SELECT a.*
    FROM table1 a
    LEFT JOIN table1 b ON a.item_id = b.item_id AND a.submit_id < b.submit_id
    WHERE b.submit_id IS NULL
) T1  ON T1.item_id = T2.item_id
INNER JOIN table3 T3 ON T1.id = T3.run_id
LEFT JOIN table4 T4
ON T3.runname_id  = T4.id
LEFT JOIN table5 ON T2.item_id = T5.item_id;