sql >> Database >  >> RDS >> Mysql

MySql Combineer twee queries (subselect of join of union)

U moet het gebruik van impliciete (door komma's gescheiden) joins laten varen ten gunste van expliciete joins. In jouw geval zijn LEFT (outer) joins geschikt.

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)

Merk op dat het meestal het beste is als de OP de gegevens levert.




  1. Extreem eenvoudige PHP en Mysql

  2. PG::Fout:SELECT DISTINCT, ORDER BY-uitdrukkingen moeten in de selectielijst verschijnen

  3. MySQL-update of hernoem een ​​sleutel in JSON

  4. MySQL PI() Functie – Retourneer de waarde van π (pi)