我有这个查询
SELECT
t2.counter_id,
t2.hash_counter,
count(1) AS cnt
FROM
table1 t1
RIGHT JOIN
table2 t2 USING(counter_id)
WHERE
t2.hash_id = 973
GROUP BY
t1.counter_id
HAVING
cnt < 8000
这是表格。
CREATE TABLE `table1` (
`id` varchar(255) NOT NULL,
`platform` varchar(32) DEFAULT NULL,
`version` varchar(10) DEFAULT NULL,
`edition` varchar(2) NOT NULL DEFAULT 'us',
`counter_id` int(11) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `counter_id` (`counter_id`)
) ENGINE=InnoDB
CREATE TABLE `table2` (
`counter_id` int(11) NOT NULL AUTO_INCREMENT,
`hash_id` int(11) DEFAULT NULL,
`hash_counter` int(11) DEFAULT NULL,
PRIMARY KEY (`counter_id`),
UNIQUE KEY `counter_key` (`hash_id`,`hash_counter`)
) ENGINE=InnoDB
“EXPLAIN”显示表 t2 的“使用索引;使用临时;使用文件排序”。有什么方法可以摆脱临时/文件排序吗?或任何其他关于优化这个人的想法。
最佳答案
您上面的评论可以让您更深入地了解您想要什么。最好更多地解释您想要实现的目标 - 仅仅查看不起作用的 SQL 就会导致人们走上错误的道路。
那么,您想知道哪些 table2
行有 < 8000 table1
行?
为什么不是这个:
select *
from table2 as t2
where hash_id = 973
and 8000 < (select count(*) from table1 as t1 where t1.counter_id = t2.counter_id)
;
关于mysql - 选择计数、分组依据并进行优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950547/