简体   繁体   中英

How do I merge these two queries together?

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

I have these tables, and in the alerts and conditions tables, they all have the device_id and object_id, but they maybe different, so I'm trying to retrieve all data of that composite.

I'm not sure I understand what you try to do but I guess you need to use UNION .

By the way why do you write WHERE 1 AND condition and not WHERE condition ?

Probably it'd be best to work on a single query, but maybe UNION would work for you as you say you just want to merge the result:

(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) ))
  • Use "UNION ALL" to allow duplicate values

You neeed to use union or union all , depending on what kind of join you want. So for twi qyery results n1 and n2 :

  • Union - x < n1+n2 - will remove duplicates
  • Union All - x == n1+n2 -will save duplicates

So your code should look like this:

(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)

You ned to remember: number and names of your query columns must match exactly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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