如何将这两个查询合并在一起?

时间:2015-08-07 21:28:16

标签: mysql sql

SELECT MIN( a.severity ), CONCAT_WS(",", a.dev_id, a.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN net.deviceinfo AS c ON c.id = a.dev_id AND 
c.peer = ( SELECT value FROM local.settings WHERE setting="server_id" ) WHERE 1 
AND (a.dev_id, a.object_id) IN ( (13,4164),(45,-1),(145,995),(188,-1) ) GROUP BY tuple


SELECT MIN( a.severity ), CONCAT_WS(",", b.device_id, b.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN local.conditions AS b ON a.condition_id = b.condition_id WHERE 1 
AND(b.device_id, b.object_id) IN ((13,4164),(45,-1),(145,995),(188,-1) ) Group BY tuple

我有这些表,在警报和条件表中,它们都有device_id和object_id,但它们可能不同,所以我试图检索该组合的所有数据。

3 个答案:

答案 0 :(得分:0)

我不确定我理解你尝试做什么,但我想你需要使用UNION

顺便说一下,为什么要写WHERE 1 AND condition而不是WHERE condition

答案 1 :(得分:0)

可能最好只处理一个查询,但是UNION会为你工作,因为你说你只想合并结果:

(SELECT MIN( a.severity ), CONCAT_WS(",", a.dev_id, a.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN net.deviceinfo AS c ON c.id = a.dev_id AND 
c.peer = ( SELECT value FROM local.settings WHERE setting="server_id" ) WHERE 1 AND 
(a.dev_id, a.object_id) IN ( (13,4164),(45,-1),(145,995),(188,-1) ))

UNION 

(SELECT MIN( a.severity ), CONCAT_WS(",", b.device_id, b.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN local.conditions AS b ON 
a.condition_id = b.condition_id WHERE 1 AND(b.device_id, b.object_id) IN ((13,4164),
(45,-1),(145,995),(188,-1) ))
  • 使用“UNION ALL”允许重复值

答案 2 :(得分:0)

您需要使用unionunion all,具体取决于您想要的加入类型。 因此,对于twi qyery结果n1n2

  • 联盟 - x < n1+n2 - 将删除重复项
  • 全部联盟 - x == n1+n2 - 将保存重复项

所以你的代码应该是这样的:

(SELECT MIN( a.severity ), CONCAT_WS(",", a.dev_id, a.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN net.deviceinfo AS c ON c.id = a.dev_id AND 
c.peer = ( SELECT value FROM local.settings WHERE setting="server_id" ) WHERE 1 
AND (a.dev_id, a.object_id) IN ( (13,4164),(45,-1),(145,995),(188,-1) ) GROUP BY tuple)

 UNION

(SELECT MIN( a.severity ), CONCAT_WS(",", b.device_id, b.object_id ) AS tuple 
FROM net.alerts AS a INNER JOIN local.conditions AS b ON a.condition_id = b.condition_id WHERE 1 
AND(b.device_id, b.object_id) IN ((13,4164),(45,-1),(145,995),(188,-1) ) Group BY tuple)

您需要记住:查询列的数量和名称必须完全匹配。