我有以下查询获取每个用户收到的最新消息("收件箱"查询):
select SQL_NO_CACHE msg.*, msg.id as msg_id, t2.count_msgs, usr.gender, usr.id,
msg.senderid as refuid from mailbox msg
inner join (select senderid,max(id) as last_msg_id,count(id) as count_msgs from mailbox where recipientid='893720' and owner='893720' and folder='inbox' group by senderid) t2 on
t2.senderid = msg.senderid and t2.last_msg_id = msg.id
left join user usr on usr.id = msg.senderid
where recipientid = '893720' order by msg.sendtime desc;
我目前有一个邮箱索引(所有者,文件夹,senderid)。解释输出:
非常感谢任何帮助。
答案 0 :(得分:1)
这是您的查询:
select SQL_NO_CACHE msg.*, msg.id as msg_id, t2.count_msgs, usr.gender, usr.id,
msg.senderid as refuid
from mailbox msg inner join
(select senderid, max(id) as last_msg_id, count(id) as count_msgs
from mailbox
where recipientid = '893720' and owner = '893720' and folder = 'inbox'
group by senderid
) t2
on t2.senderid = msg.senderid and t2.last_msg_id = msg.id left join
user usr
on usr.id = msg.senderid
where msg.recipientid = '893720'
order by msg.sendtime desc;
此版本查询的最佳索引是:mailbox(recipientid, owner, folder, senderid, id)
,mailbox(senderid,id), and
user(id)`。
第一个索引是子查询的覆盖索引(意味着它包含列)。密钥按where
子句排序。 join
需要第二个和第三个。第三个可能已经存在。
请注意,如果recipientid
和owner
确实是数字,则不要对值使用单引号。有时,使用错误的类型可能会混淆SQL优化器。