请帮助优化查询。
我有表格的字段
comment_karma
设置为1 如何获取最近7天读取最后一条消息的收藏列表。
找到最后一条消息的最佳方法是SELECT max(updated
)?
SELECT wc.comment_parent,wc.user_id, wc.updated FROM `wp_comments` wc
WHERE (wc.comment_parent IN (4786,322,1492,257,4760,40,41) AND wc.user_id=1)
AND wc.`comment_karma` = 1
AND updated = (SELECT max(`updated`) FROM `wp_comments` as cc WHERE cc.`user_id`= wc.user_id AND comment_parent = wc.comment_parent)
AND updated > DATE_SUB(NOW(),INTERVAL 1 WEEK)
ORDER BY wc.updated DESC LIMIT 0 , 30
答案 0 :(得分:2)
您的查询对我来说很好,但有其他方法可以检索相同的结果。但是 - 如果您只想选择这些列(comment_parent, user_id, updated
),则可以使用此查询:
SELECT wc.comment_parent, wc.user_id, max(wc.updated) as updated
FROM wp_comments wc
WHERE wc.comment_parent IN (4786,322,1492,257,4760,40,41)
AND wc.user_id=1
AND wc.updated > NOW() - INTERVAL 1 WEEK
AND wc.`comment_karma` = 1
GROUP BY wc.user_id, wc.comment_parent
ORDER BY max(wc.updated) desc
答案 1 :(得分:1)
您可以对查询进行优化,并为特定索引带来好处:
SELECT
wc.comment_parent,wc.user_id, wc.updated
FROM
`wp_comments` wc
WHERE
wc.comment_parent IN (4786,322,1492,257,4760,40,41)
AND wc.user_id = 1
AND wc.comment_karma = 1
AND updated =
(SELECT
max(`updated`)
FROM
wp_comments as cc
WHERE
/* put here the updated restriction,
the subquery will take care of everything */
cc.updated > now() - INTERVAL 1 WEEK
AND cc.user_id = wc.user_id
AND cc.comment_parent = wc.comment_parent
)
ORDER BY
wc.updated DESC
LIMIT
0 , 30 ;
并创建以下索引:
CREATE INDEX idx_wp_comment_rel
ON wp_comments (user_id, comment_parent, updated DESC, comment_karma) ;
索引相对较小,但它允许子查询只检查索引(所有相关数据都要检查它是否存在)。请注意,当前版本的MySQL和MariaDB识别索引中的DESC
,但不尊重它。这一天,找到最大值(更新)很简单。
您可以在 dbfiddle here
检查设置并查看执行计划