MySQL 分組後取前幾條

2021-10-02 06:15:59 字數 1247 閱讀 5352

利用group_concat和substring_index實現,能很好的利用索引,適合大資料。

select 

*from

yourtable

where

id in (select

substring_index(group_concat(id

order by column_2 desc),

',',

1) id

from

yourtable

group by column_1)

order by column_2 desc;

如果取多條,substring_index(x,x,8),通過3第三個引數來限制取會分組後的條數。外層在通過group_concat來返回所有主鍵。

由於在子查詢中,in (group_concat())會放棄索引使用,如下:

select * from yourtable where id in(

select

group_concat(id)

from

yourtable

where

id in (select

substring_index(group_concat(id

order by column_2 desc),

',',

8) id

from

yourtable

group by column_1)

order by column_2 desc

)

所以請根據explain計畫,來選擇是否用2條語句來查詢。

如果還是要一條語句,好吧。

select * from yourtable where find_in_set(id,(

select

group_concat(id) id

from

yourtable

where

id in (select

substring_index(group_concat(id

order by column_2 desc),

',',

8) id

from

yourtable

group by column_1)

order by column_2 desc

))

mysql分組取每組前幾條記錄

drop table if exists ho archives create table ho archives id mediumint 11 unsigned not null auto increment comment 自增id type smallint 5 unsigned not n...

Mysql取分組後前N個值

表結構如下 create table test group limit row id varchar 33 id int 11 num bigint 11 log varchar 33 insert into test group limit row id id num log values 1 1...

sql取分組的前幾條 指定條數

注 sqlserver下 create table test areaid int,score int insert into test select 0,10 union all select 0,20 union all select 0,30 union all select 0,40 uni...