MySQL在三个表上编写连接

时间:2017-12-20 02:43:16

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

我编写了以下mysql查询

SELECT distinct name, date
FROM table1
JOIN table2 ON (table2.item_id = table1.item_id)
where table1.id IN (SELECT run_id FROM 
table3 where table3.status = 'FAIL') and table1.createdate >= '2011-01-01'
 ; 

我想在输出中添加message中的其他字段table3

我想这可能涉及在查询中加入3个表。 请告诉我如何实现这一目标。

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT distinct name, date, T3.message
FROM table1
JOIN table2 ON (table2.item_id = table1.item_id) 
INNER JOIN (SELECT run_id FROM 
table3 where status = 'FAIL') T3 ON T3.run_id = table1.id
where table1.createdate >= '2011-01-01'

答案 1 :(得分:1)

试试这个: -

SELECT DISTINCT T1.NAME , T1.DATE , T3.MESSAGE
FROM TABLE1 T1
JOIN TABLE2 T2
ON
T1.ITEM_ID = T2.ITEM_ID
INNER JOIN TABLE3 T3
ON
T1.ID = T3.RUN_ID
WHERE T3.STATUS = 'FAIL' AND T1.CREATEDATE >= '2011-01-01';

答案 2 :(得分:1)

没有足够的信息来完全回答这个问题。我们也想知道:

  1. status列是来自table1还是来自table3
  2. 是否可以存在多个table3条记录,runidtable1.id值匹配?
  3. 如果可以,您希望显示哪个table3.message值?
  4. 如果不知道这些信息,我们所能做的就是猜测。这是我的猜测:

    SELECT distinct name, date, message
    FROM table1 t1
    INNER JOIN table2 t2 ON t2.item_id = t1.item_id
    INNER JOIN table3 t3 on t1.id =t3.run_id AND t3.status = 'FAIL'
    WHERE t1.createdate >= '2011-01-01'
    

答案 3 :(得分:0)

试试这个:

从table1 t1,table2 t2,table3 t3中选择不同的名称,日期和消息,其中t1.item_id = t2.item_id和t1.item_id = t3.item_id 和t3.status ='失败' AND t1.createdate> = to_date(' 2011-01-01,' YYYY-DD-MM');