【问题标题】:Adding fifth join in the table在表中添加第五个连接
【发布时间】:2018-02-08 18:52:28
【问题描述】:

到目前为止,我已经编写了以下 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。我想在item_id 上加入table5table2,并想在我的最终查询中检索restoreid 的值。

item_id  restoreId
15907       12342
7303        12342
7304        14342
7305        14342

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

【问题讨论】:

  • 您没有正确加入 T3 和 T4。你错过了(T)。试试我提供的答案

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


【解决方案1】:
select your_table.fault,your_table.name,t5.restoreid
from (
    SELECT 
    T3.fault, t4.name,t2.item_id
    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
) as your_table left join table5 t5 on your_table.item_id = t5.item_id 

【讨论】:

  • 我收到错误syntax error unexpected your_table
  • 抱歉,现在试试。
  • 是的,伙计们。立即尝试
  • 您好,感谢您的询问。我不希望 item_id 显示在最终输出中。有没有办法省略?
  • 是的,我修改了查询。
【解决方案2】:
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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多