表结构如下
CREATE TABLE `table` (
`id` bigint(20) NOT NULL auto_increment,
'type' int(11),
'update' date
)
查询按type分组后,每组的最新20条数据
CREATE TABLE `table` (
`id` bigint(20) NOT NULL auto_increment,
'type' int(11),
'update' date
)
查询按type分组后,每组的最新20条数据
所以,希望找到其他效率较高的sql
from `table` a
where 20> (select count(*) from `table` where 'type'=a.'type' and 'update'>a.'update')
create index idx_table_test on `table` ('type','update')
(select * from table where type = 1 order by update desc limit 20)
union all
(select * from table where type = 2 order by update desc limit 20)
union all
(select * from table where type = 3 order by update desc limit 20)
这个花了400多ms
而你 #5楼 的时间复杂度是 n*O, 所以#5楼 的显然快。 但前提是你需要事先知道distinct type 的 ,这样就不是通过一条SQL语句来实现。 你可以在你的程序中或者在存储过程中来通过分步来实现。
贴出来看一下结果是什么?
explain select * from table where type = 1 order by update desc limit 20;
的结果
1 |SIMPLE |active_h |ref |active_h_type| active_h_type |5 |const |17616 |Using where; Using filesort
SET engine_condition_pushdown=ON;
SET engine_condition_pushdown=1;前提是你把type和update索引去掉如此设置试试看
但是在5.1版本的mysql 只支持DNBCLUSTER引擎
1 |SIMPLE |active_h |ref |active_h_type| active_h_type |5 |const |17616 |Using where; Using filesort有 Using filesort ?show index from `table` 看一下,另外你的这个 explain 是 explain select * from table where type = 1 order by update desc limit 20; 吗?好象并不一样啊!
Key_name Seq_in_index Column_name
-------- ------ ------ ---------- -------
PRIMARY 1 id
a_t 1 active_time
active_h_type 1 active_type
谢谢,版主辛苦了~
我又加了个限制条件,让他少差了些数据,就快了,100多ms搞定
a_t 1 active_time
active_h_type 1 active_type
方案 1:(于版主同)
select * from `table` a where 20> (select count(*) from `table` where 'type'=a.'type' and 'update'>a.'update')方案 2:
select * ,rank from (
select b.*,@rownum:=@rownum+1 ,
if(@btype=b.ype,@rank:=@rank+1,@rank:=1) as rank,
@btype:=b.type
from (
select * from table order by type asc, update desc)
b,(select @rownum :=0 ,@btype:=null,@rank:=0)a ) result where rank<20方案3:
就是我在15楼说的(select * from table where type = 1 order by update desc limit 20)
union all
(select * from table where type = 2 order by update desc limit 20)
union all
(select * from table where type = 3 order by update desc limit 20)
方案3 的限制是要知道type ,而且type的数量较少,而表中的纪录数较多