我正在为我的查询寻找解决方案,以改善表现。
我刚刚阅读了几篇关于此事的帖子,但(也许是为了引起我)他们并不适合我的案例。 无论如何,这是我的问题。
我的msg表格如下:
IDMSG |线程| SENDER |接收器|日期|味精| READ
1521年| 2 | 20 | 43 | 05/24/2014 |你好,伙计们01522 | 3 | 84 | 43 | 05/24/2014 |嗨男人| 0
1523 | 2 | 20 | 43 | 05/24/2014 |是的,是的0
现在,您将看到用户20已经向我写了2个消息(43),因此,在我的msg索引页面上,我想打印最新的消息,并排序它是公正的。
例如:
目前,我真正的疑问是:
SELECT * FROM
(SELECT * FROM boxmsg
LEFT JOIN user ON sender = id WHERE receiver = '959749'
ORDER BY idmsg DESC)
AS temp_tbl
GROUP BY thread ORDER BY idmsg DESC LIMIT 0,20
所以,它运作正常,但性能是一场真正的灾难。 实际上,它扫描整个数据库,因为派生表中的索引有几个问题。
如何获得相同的结果,拥有最新的线程消息?
谢谢你,对不起我糟糕的英语。
答案 0 :(得分:1)
这是您的查询:
SELECT *
FROM (SELECT *
FROM boxmsg LEFT JOIN
user
ON sender = id
WHERE receiver = '959749'
ORDER BY idmsg DESC
) temp_tbl
GROUP BY thread
ORDER BY idmsg DESC
LIMIT 0, 20;
MySQL特别警告*
group by
与SELECT *
FROM boxmsg bm LEFT JOIN
user
ON sender = id
WHERE receiver = '959749' AND
NOT EXISTS (SELECT 1
FROM boxmsg bm2
WHERE bm2.receiver = bm.receiver and
bm2.thread = bm.thread and
bm2.idmsg > bm.idmsg
)
ORDER BY idmsg DESC
LIMIT 0, 20;
的使用(见here)。
要执行以下操作,请尝试以下查询:
boxmsg(receiver, thread, idmsg)
在运行查询之前,在user(id)
上创建一个索引,在{{1}}上创建一个索引(如果已经存在的话)。
答案 1 :(得分:0)
类似的东西:
SELECT b.*
FROM boxmsg b
JOIN (
SELECT thread, MAX(idmsg) as idmsg
FROM boxmsg x
GROUP BY thread
) a
ON a.thread = b.thread
AND a.idmsg = b.idmsg
线程索引,idmsg可能有助于提高性能