日期:2014-05-16 浏览次数:20865 次
create table subcategory ( id int not null primary key, category int not null, index(category) ) engine=InnoDB; create table item( id int not null auto_increment primary key, subcategory int not null, index(subcategory) ) engine=InnoDB;
insert into subcategory(id, category) select i, i/100 from number where i <= 300000; insert into item(subcategory) select id from ( select id, rand() * 20 as num_rows from subcategory ) as x cross join number where i <= num_rows; create temporary table t as select subcategory from item group by subcategory having count(*) = 19 limit 100; insert into item (subcategory) select subcategory from t cross join number where i < 2000;
select c.id from subcategory as c inner join item as i on i.subcategory = c.id group by c.id having count(*) > 2000; -- choose one of the results, then select * from subcategory where id = ???? -- result: category = 14
select c.id from subcategory as c inner join item as i on i.subcategory = c.id where c.category = 14 group by c.id having count(*) > 2000;
select * from subcategory where id in ( select c.id from subcategory as c inner join item as i on i.subcategory = c.id where c.category = 14 group by c.id having count(*) > 2000 );
*************************** 1. row *************************** id: 1 select_type: PRIMARY table: subcategory type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 300783 Extra: Using where *************************** 2. row *************************** id: 2 select_type: DEPENDENT SUBQUERY table: c type: ref possible_keys: PRIMARY,category key: category key_len: 4 ref: const rows: 100 Extra: Using where; Using index; Using temporary; Using filesort *************************** 3. row *************************** id: 2 select_type: DEPENDENT SUBQUERY table: i type: ref possible_keys: subcategory key: subcategory key_len: 4 ref: c.id rows: 28 Extra: Using index
select * from subcategory as s where <in_optimizer>( s.id,<