I’m trying to join a query results on a field, ‘min’ – which is the hour:min of the event. I have two different select queries in one and I’m trying UNION (which may not be right, just trying different things, I find MySQL documentation very difficult to read).
So I want
H:M and then the result of addCount and projectsNum – so for each hour/min I have the stats.
Where am I going wrong?
(
SELECT
DATE_FORMAT(`when`, '%H:%i') as `min`,
COUNT(`ipAddress`) AS `addCount`
FROM `metric` m
WHERE `when` BETWEEN DATE_SUB(NOW(), INTERVAL 3 HOUR) AND NOW()
GROUP BY DAY(`when`), HOUR(`when`), MINUTE(`when`)
)
UNION
(
SELECT
DATE_FORMAT(v.`created`, '%H:%i') as `min`,
COUNT(v.`projID`) as `projectsNum`
FROM `projects` v
WHERE v.`created` BETWEEN DATE_SUB(NOW(), INTERVAL 3 HOUR) AND NOW()
GROUP BY DAY(v.`created`), HOUR(v.`created`), MINUTE(v.`created`)
)
UNIONjust appends a set of results to another set of results.You need to use your second query as a sub-query:
This query probably performs terribly. I just brute-force copy-pasted from your original query to make it syntactically correct, but there must be a way to optimize it.