繁体   English   中英

MySQL 将两个查询合并为一个查询

[英]MySQL combining two queries into single query

我的第一个查询如下所示

SELECT a.name, b.desc, T3.desc1 as Output
FROM table1 a INNER JOIN
     table2 b
     ON a.id = b.id
INNER JOIN (
  SELECT b2.id, b2.status,  MAX(b2.created_time) as max_time
  FROM q_scan b2
  GROUP BY b2.id  ,  b2.qualys_type
  ) t on t.id = a.id
      AND  t.status=b.status
      AND t.max_time = b.created_time
INNER JOIN table3 T3 on b.tid = T3.tid
WHERE b.status = 'FAIL'

我的第二个查询如下所示

SELECT a.name, b.desc, T4.desc2 as Output
FROM table1 a INNER JOIN
     table2 b
     ON a.id = b.id
INNER JOIN (
  SELECT b2.id, b2.status,  MAX(b2.created_time) as max_time
  FROM q_scan b2
  GROUP BY b2.id  ,  b2.qualys_type
  ) t on t.id = a.id
      AND  t.status=b.status
      AND t.max_time = b.created_time
INNER JOIN table4 T4 on b.tid = T4.tid
WHERE b.status = 'FAIL'

在我的最终结果中,我想要Output column ,它的值来自T3.desc1T4.desc2如何将两个查询组合成一个查询?

如果table2.id存在于其中一个表 - table3table4中, LEFT JOIN将在IFNULL()的帮助下简化查询。

SELECT  a.name, 
        b.desc, 
        IFNULL(T3.desc1, T4.desc2) as Output
FROM    table1 a 
        INNER JOIN table2 b ON a.id = b.id
        INNER JOIN 
        (
            SELECT b2.id, b2.status,  MAX(b2.created_time) as max_time
            FROM oac.qualys_scan b2
            GROUP BY b2.id  ,  b2.qualys_type
        ) t on t.id = a.id
              AND  t.status=b.status
              AND t.max_time = b.created_time
        LEFT JOIN table3 T3 on b.tid = T3.tid
        LEFT JOIN table4 T4 on b.tid = T4.tid
WHERE   b.status = 'FAIL'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM