在mysql join中添加第四个表

时间:2018-01-29 21:33:34

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

我编写了一个包含3个连接和3个表的查询,如下所示:

SELECT 
T3.fault, count(*)
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
group by T3.fault
order by count(*) desc;

我的table3如下所示:

id      run_id  runname_id  status  fault
134049  16736   312         FAIL    error1
134050  16736   313         FAIL    error2
134051  16736   314         FAIL    error3
134052  16736   315         PASS    error4
134053  16736   316         PASS    error5

我有一个静态表table4,如下所示:

id  name
312 name1
313 name2
314 name3
315 name4
316 name5

我想在查询中加入table4,以便我的输出也应包含name中的table4。每个errorname中都有相应的table4我想要包含该名称

fault   count(*) name
error1  6        name1

2 个答案:

答案 0 :(得分:1)

只有LEFT JOIN table4T4.name列到所选列列表。

SELECT 
T3.fault, count(*), 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
group by T3.fault
order by count(*) desc;

答案 1 :(得分:1)

我会做这样的事情。

SELECT A.fault, A.count, T4.name FROM TABLE4 T4 JOIN(
SELECT 
T3.fault as fault, count(*) as count, T3.run_id as run_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
group by T3.fault) A ON A.run_id = T4.id
order by A.count desc;

没有测试过,但据我所知,它只是将第4个表与子查询表合并。因此,您的查询将返回带有fault,count和id的结果。然后我们将此表与id上的表4合并,并按desc对计数进行排序。 如果我对这个问题有错误的理解,请纠正我