选择计数,分组和优化

时间:2014-04-09 00:11:46

标签: mysql sql

我有这个查询

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

&#34; EXPLAIN&#34;显示&#34;使用索引;使用临时;使用filesort&#34;对于表t2。有没有办法摆脱临时/ filesort?或者关于优化这个人的任何其他想法。

1 个答案:

答案 0 :(得分:1)

您的上述评论可让您更深入地了解自己的需求。总是更好地解释一下你想要实现的目标 - 只要看一下非工作的SQL就会导致人们走错路。

所以,你想知道哪些table2行有&lt; 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)
 ;
相关问题