如果column为null,则选择Max()列不会返回

时间:2014-09-23 23:21:21

标签: mysql sql greatest-n-per-group

我有这样的查询

SELECT cus.id, cus.crawler_url_id, cus.created_at, cus.status
FROM crawler_url_stats cus
INNER JOIN (
    SELECT id, crawler_url_id, max( created_at ) latest
    FROM crawler_url_stats
    GROUP BY crawler_url_id
) cus2 ON ( cus.crawler_url_id = cus2.crawler_url_id
AND cus.created_at = cus2.latest )
ORDER BY `cus`.`crawler_url_id` ASC 

这是在其他一个主题中提出的一个小修改版本的查询,我刚刚将内部查询中的GROUP BY更改为crawler_url_id(它不是id)并更改了匹配也加入crawler_url_id

所有内容似乎都运行良好,但是created_at之一的行crawler_url_id为空时出现问题,例如我有4行crawler_url_id等于{{ 1}}如果只有其中一个5等于created_at,则结果不会包含null 5的结果。

对我来说似乎很奇怪,首先我尝试了这篇帖子https://stackoverflow.com/a/7745635/1951693中的代码,但它返回了错误的结果(每个crawler_url_id多个结果)所以我修改了它,现在它只是在那里挣扎在那里是空的。

2 个答案:

答案 0 :(得分:1)

尝试从子查询中排除NULL行:

SELECT cus.id, cus.crawler_url_id, cus.created_at, cus.status
FROM crawler_url_stats cus
INNER JOIN (
    SELECT id, crawler_url_id, max( created_at ) latest
    FROM crawler_url_stats
    WHERE created_at IS NOT NULL
    GROUP BY crawler_url_id
) cus2 ON ( cus.crawler_url_id = cus2.crawler_url_id
AND cus.created_at = cus2.latest )
ORDER BY `cus`.`crawler_url_id` ASC 

答案 1 :(得分:0)

在两个子查询中设置max(ifnull(created_at, 0))而不是cus.created_at,效果很好。解决。