P粉7104789902023-09-01 21:08:35
嗯,也许你可以尝试为你的表添加索引:https://www.drupal.org/docs/7/guidelines-for-sql/the-benefits-of-indexing-large-mysql-tables#:~:text=Creating%20Indexes&text=The%20statement%20to%20create%20index,the%20index%20must%20be%20distinct。 确保按照你查询的行添加组合索引。
如果这样做没有改善你的查询时间,那么应该改进查询。
P粉0200855992023-09-01 14:23:17
注意:
CONCAT-LEAST-GREATEST - 这是为了构造一个“friends_id”?也许你真正想要一个“conversation_id”?目前,两个用户永远不会有多个“conversation”,对吗?
如果确实需要,为conversation_id创建一个新列。(目前,GROUP BY是低效的。)下面的代码消除了对这样一个id的需求。
( SELECT lastid FROM ( ( SELECT from_id, MAX(id) AS lastid FROM messages WHERE to_id = ? GROUP BY from_id ) UNION DISTINCT ( SELECT to_id, MAX(id) AS lastid FROM messages WHERE from_id = ? GROUP BY to_id ) ) AS x ) AS conversations
并且拥有这些“covering”和“composite”索引:
INDEX(to_id, from_id, id) INDEX(from_id, to_id, id)
删除KEY(to_id),KEY(from_id),因为我的新索引可以处理这两个索引的所有其他任务。
我认为这具有相同的效果,但运行速度更快。
将它们组合起来:
SELECT * FROM ( ( SELECT from_id AS other_id, MAX(id) AS lastid FROM messages WHERE to_id = ? GROUP BY from_id ) UNION ALL ( SELECT to_id AS other_id, MAX(id) AS lastid FROM messages WHERE from_id = ? GROUP BY to_id ) ) AS latest JOIN messages ON messages.id = latest.lastid ORDER BY messages.id DESC
(加上这两个索引)
更多
我曾经错误地认为UNION DISTINCT可以替代对conversation_id的需求。但事实并非如此。我立即看到了一些解决方案: