MYSQL使用Union来组合两个查询

时间:2018-02-28 15:20:17

标签: mysql sql join inner-join union

我的第一个查询如下所示

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 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
INNER JOIN table3 T3 on b.tid = T3.tid
WHERE b.status = 'FAIL'
AND b.type = 'Type1'

我的第二个查询如下所示

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 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
INNER JOIN table4 T4 on b.tid = T4.tid
WHERE b.status = 'FAIL'
AND b.type = 'Type2'

在我的最终结果中,我希望Output column的值为T3.desc1T4.desc2 如何使用UNION将两个查询合并到一个查询中?

2 个答案:

答案 0 :(得分:0)

只需在查询之间放置UNION ALL。你必须为列添加别名

答案 1 :(得分:0)

这样做:

Query1 UNION Query2; -- for union without duplicates (the set union as in maths)

OR

Query1 UNION ALL Query2; -- for union with duplicates

所以它应该是:

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 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
INNER JOIN table3 T3 on b.tid = T3.tid
WHERE b.status = 'FAIL'
AND b.type = 'Type1'

UNION

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 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
INNER JOIN table4 T4 on b.tid = T4.tid
WHERE b.status = 'FAIL'
AND b.type = 'Type2';