关于MYSQL中每个用户取1条记录的三种写法(group by xxx)
程序员文章站
2024-02-25 22:30:39
今天以前的同学问我关于这方面的sql语句,我特意记忆一下,毕竟这个也比较常见了复制代码 代码如下:select * from (select * from member_p...
今天以前的同学问我关于这方面的sql语句,我特意记忆一下,毕竟这个也比较常见了
select * from (select * from member_payment
order by id desc) t group by member_id limit 10
第一种是先排序,然后group,这样的话自然可以取到最适合的一条数据。
缺点很明显:using temporary; using filesort
select s.*
from (select max(id) as id from `member_payment` group by `member_id` limit 10) t
left join `member_payment` as s on t.id=s.id
第二种是联合查询
select * from `member_payment` where exists (
select `id` from (
select max(`id`) as id from `member_payment` group by `member_id` limit 10) t
where t.`id`=`member_payment`.`id`
)
第三种是子查询
窃以为第二种效率最高
复制代码 代码如下:
select * from (select * from member_payment
order by id desc) t group by member_id limit 10
第一种是先排序,然后group,这样的话自然可以取到最适合的一条数据。
缺点很明显:using temporary; using filesort
复制代码 代码如下:
select s.*
from (select max(id) as id from `member_payment` group by `member_id` limit 10) t
left join `member_payment` as s on t.id=s.id
第二种是联合查询
复制代码 代码如下:
select * from `member_payment` where exists (
select `id` from (
select max(`id`) as id from `member_payment` group by `member_id` limit 10) t
where t.`id`=`member_payment`.`id`
)
第三种是子查询
窃以为第二种效率最高