0

我正在尝试在“分钟”字段上加入查询结果 - 这是事件的小时:分钟。我有两个不同的选择查询,我正在尝试 UNION (这可能不对,只是尝试不同的东西,我发现 MySQL 文档很难阅读)。

所以我想要

H:M 然后是 and 的结果addCount-projectsNum所以对于每一小时/分钟我都有统计数据。

我哪里错了?

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

1 回答 1

1

UNION只是将一组结果附加到另一组结果。

您需要将第二个查询用作子查询:

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

这个查询可能执行得很糟糕。我只是从您的原始查询中强力复制粘贴以使其在语法上正确,但必须有一种优化它的方法。

于 2012-06-14T01:21:27.777 回答