MySQL分組排序,mysql分組

來源:互聯網
上載者:User

MySQL分組排序,mysql分組

一、問題

產品表
有平台id 產品名稱

id ptid name
1 100 產品1
2 100 產品2
3 100 產品3
4 100 產品4
5 100 產品5
6 100 產品6
7 101 產品7
8 101 產品8
9 101 產品9
10 101 產品10
11 101 產品11

如何根據某個平台id 只取這個平台的3條資料(順序可以隨機)

id ptid name
1 100 產品1
2 100 產品2
3 100 產品3
7 101 產品7
8 101 產品8
9 101 產品9


二、建表

create table p_a(  id int,  ptid varchar(20),  name varchar(20))insert into p_a(id,ptid,name) values(1,'100','產品1');insert into p_a(id,ptid,name) values(2,'100','產品2');insert into p_a(id,ptid,name) values(3,'100','產品3');insert into p_a(id,ptid,name) values(4,'100','產品4');insert into p_a(id,ptid,name) values(5,'100','產品5');insert into p_a(id,ptid,name) values(6,'100','產品6');insert into p_a(id,ptid,name) values(7,'101','產品7');insert into p_a(id,ptid,name) values(8,'101','產品8');insert into p_a(id,ptid,name) values(9,'101','產品9');insert into p_a(id,ptid,name) values(10,'101','產品10');insert into p_a(id,ptid,name) values(11,'101','產品11');

三、sql

select * from (select a.*,case when @oldptid=ptid then @lagfield:=@lagfield+1 else @lagfield:=1 end rn,@oldptid:=ptidfrom p_a a,(select @lagfield:=0,@oldptid:='') r) a where rn<=3


四、總結

MySQL根據ptid分組,分別對分組內進行標註序號,然後根據序號取出各分組內的記錄

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.