优化SQL查询“ SELECT”

时间:2018-07-18 03:04:15

标签: mysql database mariadb

如何优化此查询

SELECT count(*) FROM chats WHERE removeAt = 0
SELECT count(*) FROM messages WHERE removeAt = 0
SELECT count(*) FROM messages WHERE chatId = (:chatId) AND removeAt = 0
SELECT count(*) FROM chats WHERE (fromUserId = (:userId) OR toUserId = (:userId)) AND removeAt = 0

该查询的我的QPS大约1200

2 个答案:

答案 0 :(得分:0)

这一次获得2个值。因此,速度加倍。

SELECT COUNT(*) AS not_removed,
       SUM(chatId = (:chatId)) AS that_id
    FROM chats
    WHERE removeAt = 0;

答案 1 :(得分:-1)

如果您要询问如何优化数据库以更快地返回查询结果,则第一步应该是为chats.removeAt, chats.fromUserId, chats.toUserId, messages.removeAt, messages.chatId构建索引