sql >> Base de Datos >  >> RDS >> Mysql

MySql Combinar dos consultas (subseleccionar o unir o unir)

Debe abandonar el uso de uniones implícitas (separadas por comas) en favor de uniones explícitas. En su caso, las uniones LEFT (externas) son apropiadas.

DROP  TABLE  IF EXISTS  Hosts;
DROP  TABLE  IF EXISTS  Items;
DROP  TABLE  IF EXISTS  History_unit;
DROP  TABLE  IF EXISTS  History_uint;
DROP  TABLE  IF EXISTS  History_log;

CREATE TABLE Hosts(host VARCHAR(20), hostid INT);
CREATE TABLE Items(hostid INT, itemid INT, name VARCHAR(20));
CREATE TABLE History_uint(itemid INT, value INT);
CREATE TABLE History_log(itemid INT, value INT);

INSERT INTO HOSTS VALUES ('HOST1',1),('HOST2',2);
INSERT INTO ITEMS VALUES
(1,1,'RP_Dayend_OK'),
(1,2,'RP_Sync_OK'),
(1,3,'RP_Monthend_OK'),
(1,4,'RP_Version' ),
(2,1,'RP_Dayend_OK'),
(2,2,'RP_Sync_OK'),
(2,2,'RP_cron')
;
INSERT INTO HISTORY_uint VALUES
(1,10),(2,10),(3,10),(4,10),
(1,50),(3,60);

INSERT INTO HISTORY_log VALUES
(1,10),(2,10),(3,10),(4,10)
;

SELECT hosts.host, 
max((case when items.name='RP_Dayend_OK' then history_uint.value end) *1000) as 'Day End', 
max((case when items.name='RP_Sync_OK' then history_uint.value end) *1000) as 'Sync',
max((case when items.name='RP_Monthend_OK' then history_uint.value end) *1000) as 'Month End', 
max(case when items.name='RP_Version' then history_uint.value end) as 'Version',
max(case when items.name='RP_Cron' then history_log.value end) as 'cron'
from hosts
left join  items on items.hostid = hosts.hostid
left join  history_uint on history_uint.itemid = items.itemid
left join  history_log on history_log.itemid = items.itemid
where items.name like '%RP\_%'
group by hosts.host;

+-------+---------+-------+-----------+---------+------+
| host  | Day End | Sync  | Month End | Version | cron |
+-------+---------+-------+-----------+---------+------+
| HOST1 |   50000 | 10000 |     60000 |      10 | NULL |
| HOST2 |   50000 | 10000 |      NULL |    NULL |   10 |
+-------+---------+-------+-----------+---------+------+
2 rows in set (0.00 sec)

Tenga en cuenta que generalmente es mejor si el OP proporciona los datos.