使用Distinct的MYSQL查询优化

时间:2018-09-17 06:17:10

标签: mysql

我想找到每天通过通知访问该应用程序的用户数。我写的查询非常慢。

SELECT DATE(user_statistics.timestamp) date, COUNT(*) count FROM post
INNER JOIN user_statistics ON user_statistics.post_id = post.id
AND user_statistics.access_type = 'notification' AND post.type = 'given_type'
GROUP BY DATE(user_statistics.timestamp)

我重写了它,以使用DISTINCT使其更快。

SELECT DISTINCT date(user_statistics.timestamp), count(DISTINCT user_statistics.post_id) 
FROM user_statistics INNER JOIN post on post.id = user_statistics.post_id
WHERE post.type = 'given_type' AND access_type = 'notification'

新查询不起作用。它说

  

在没有GROUP BY的聚合查询中,SELECT列表的表达式#1   包含未汇总的列“ user_statistics.timestamp”;这个   与sql_mode = only_full_group_by

不兼容

1 个答案:

答案 0 :(得分:2)

您忘记添加group by子句:

SELECT DISTINCT date(user_statistics.timestamp), count(DISTINCT user_statistics.post_id) 
FROM user_statistics INNER JOIN post on post.id = user_statistics.post_id
WHERE post.type = 'given_type' AND access_type = 'notification'
group by date(user_statistics.timestamp)