我想知道哪个查询更好。我想在表格中选择一些特定记录和所有记录计数(但已过滤)。
哪个查询更好?
SELECT name, surname,
(select COUNT(messages.id) from messages WHERE `messages`.`archived` = '0' AND `type` IN (0, 1) ) as count
FROM messages JOIN
users
ON users.id = messages.user_id
WHERE messages.archived = 0 AND type = 0 OR type = 1
ORDER BY created_on DESC
LIMIT 3
或
SELECT name, surname
FROM messages JOIN
users
ON users.id = messages.user_id
WHERE messages.archived = 0 AND type = 0 OR type = 1
ORDER BY created_on DESC
LIMIT 3
带
SELECT count(id) as count
FROM messages
WHERE `messages`.`archived` = '0' AND `type` IN (0, 1)
如果我有大数据库,我会检查这个,但是现在我有一些记录。
使用单个查询,计数将添加到每条记录中。
谢谢,对不起我的英文!
答案 0 :(得分:1)
写完这篇文章后,我意识到两个查询不一样。因此,您应该使用与您想要获得的结果相对应的版本。 (你想过滤计数吗?)
我不确定MySQL是否会优化SELECT
中的子查询。但是,您只需将其移动到FROM
子句中,它只运行一次:
SELECT `name`, `surname`, m.cnt
FROM `messages` JOIN
`users`
ON `users`.`id` = `messages`.`user_id` CROSS JOIN
(select COUNT(messages.id) as cnt from messages) m
WHERE `messages`.`archived` = '0' AND `type` = 0 OR `type` = 1
ORDER BY `created_on` DESC;
LIMIT 3
我怀疑你的WHERE
条款不正确。你真的打算这个吗?
WHERE `messages`.`archived` = '0' AND `type` IN (0, 1)