您现在的位置是: 首页 > MySQL MySQL
SQL取分组的前几条/指定条数(原生SQL与TP6写法)
冬寂 2022-05-20 15:12:46 【MySQL】 3631人已围观
SQL取分组的前几条/指定条数(原生SQL与TP6写法)
原生SQL
SELECT * FROM `sdsd` `a` WHERE EXISTS ( SELECT count(*) FROM `sdsd` `b` WHERE ( a.type=b.type ) AND ( a.id>b.id ) HAVING count(*)<2 ) ORDER BY `a`.`type` DESC
Thinkphp6写法
Db::name('sdsd')->alias('a')
->whereExists(function ($query){
$query->table('sdsd')->alias('b')
->fieldRaw('count(*)')
->whereRaw('a.type=b.type')
->whereRaw('a.id>b.id')
->having('count(*)<2');
})
->order('a.type','desc')
->select()->toArray();