代码之家  ›  专栏  ›  技术社区  ›  meallhour

在mysql连接中添加第四个表

  •  1
  • meallhour  · 技术社区  · 8 年前

    我编写了一个涉及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
    

    我想包括 表4 以便我的输出还应包括 name 从…起 表4 . 每一个 error 具有相应的 名称 在里面 表4 我也想包括这个名字

    fault   count(*) name
    error1  6        name1
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Alex    8 年前

    所以只要 LEFT JOIN 那个 table4 和 T4.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;
    
        2
  •  1
  •   Dwipam Katariya    8 年前

    我会这样做。

    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;
    

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

    推荐文章