在结果字段上加入两个选择查询

时间:2012-06-13 11:11:13

标签: php mysql select join union

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

所以我想要

H:M然后是addCountprojectsNum的结果 - 所以每小时/分钟我都有统计数据。

我哪里错了?

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

1 个答案:

答案 0 :(得分: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`)

此查询可能执行得非常糟糕。我只是粗暴地从原始查询中复制粘贴以使其在语法上正确,但必须有一种方法来优化它。