Mysql 查詢需要 15 秒以上的時間來獲取資料。我在下面給出了我的查詢。
僅供參考:訊息表有5L(500,000)行資料,因此需要很長時間。
select distinct
ur.id, ur.user_name as name, ur.online, ur.chat_status,
ur.updated_at, ur.profile_image, ur.role_id,
( SELECT created_at
from messages
where from_role_user_id = ur.id
OR to_role_user_id = ur.id
Order by created_at DESC
LIMIT 1
) as message_at,
( SELECT count(is_read)
from messages
where from_role_user_id = ur.id
AND to_role_user_id = 1
AND is_read = 0
) as count,
r.name as role
from role_users ur
left join roles r ON r.id = ur.role_id
where ur.id != 1
AND r.name IN ('superadmin', 'candidate', 'admin', 'manager',
'business_unit','client')
AND ur.chat_status != 'offline'
AND ur.is_deleted = 0
AND ur.user_name IS NOT NULL
order by message_at DESC
LIMIT 10;
任何人都可以幫助我優化查詢。
uj5u.com熱心網友回復:
這樣第一個子查詢可能會更快:
( SELECT MAX(created_at) from messages where from_role_user_id = ur.id OR to_role_user_id = ur.id ) as message_at,這可能更快:
SELECT GREATEST( ( SELECT MAX(created_at) FROM messages WHERE from_role_user_id = ur.id ), ( SELECT MAX(created_at) FROM messages WHERE to_role_user_id = ur.id ) )有兩個索引:
索引(from_role_user_id,created_at),索引(to_role_user_id,created_at)
COUNT(x)計算有多少行x IS NOT NULL。SUM(y)將 y 相加,忽略NULLs. 計算行數的常用方法是COUNT(*).( SELECT count(*) from messages where from_role_user_id = ur.id AND to_role_user_id = 1 AND is_read = 0 ) as count,并有`INDEX(from_role_user_id, to_role_user_id, is_read)
如果
DISTINCT不是真的需要,它將避免額外的資料傳遞,因此更快。請提供
EXPLAIN SELECT ...這可能是更好的找到10條訊息的ID第一,然后去上LY 10次運行這些子查詢的努力。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333552.html
上一篇:使用set文字更快地設定包含
下一篇:洗掉小于陣列左側元素的元素
