在where子句中使用max的日期差异

时间:2019-03-06 12:19:56

标签: mysql sql mysqli mariadb mariasql

以下查询中有group by子句错误。我不知道如何使它正确

SELECT user_id, MAX(updated_date), DATEDIFF(NOW(),MAX(updated_date))
FROM `authentication`
WHERE DATEDIFF(NOW(),MAX(updated_date)) > 20
GROUP by user_id

3 个答案:

答案 0 :(得分:1)

大概您想要一个having子句:

SELECT user_id, MAX(updated_date), 
       DATEDIFF(NOW(), MAX(updated_date)) as diff
FROM `authentication`
GROUP by user_id
HAVING diff > 20

答案 1 :(得分:0)

无需在MAX()子句中进行WHERE

SELECT user_id, MAX(updated_date), DATEDIFF(NOW(),MAX(updated_date))
FROM `authentication`
WHERE DATEDIFF(NOW(),updated_date) > 20
GROUP by user_id

答案 2 :(得分:0)

为了提高性能,请使用进一步修改其他答案之一

WHERE updated_date > CURDATE() - INTERVAL 20 DAY

和索引updated_date