Joining two select queries on a results field

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

Answers


UNION just appends a set of results to another set of results.

You need to use your second query as a sub-query:

SELECT
    DATE_FORMAT(`when`, '%H:%i') as `min`,
    COUNT(`ipAddress`) AS `addCount`,
    projects_subquery.`projectsNum`
FROM `metric` m
JOIN (

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

) AS projects_subquery ON projects_subquery.`min` = m.`min`
WHERE `when` BETWEEN DATE_SUB(NOW(), INTERVAL 3 HOUR) AND NOW()
GROUP BY DAY(`when`), HOUR(`when`), MINUTE(`when`)

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.


Need Your Help

Draw a rectangle on mouse click

c# winforms drawing

Can I draw a rectangle with mouseClick? My code is not working so far. Can you help me?