Home > Database > Mysql Tutorial > MYSQL每个用户取1条记录的三种写法(group by xxx)_MySQL

MYSQL每个用户取1条记录的三种写法(group by xxx)_MySQL

WBOY
Release: 2016-06-01 13:34:09
Original
1378 people have browsed it

bitsCN.com

MYSQL每个用户取1条记录的三种写法(group by xxx)

 

同学问我关于这方面的SQL语句,我特意记忆一下,毕竟这个也比较常见了

 

[sql] 

select * from (select * from member_payment   

                order by id desc) t group by member_id limit 10  

第一种是先排序,然后group,这样的话自然可以取到最适合的一条数据。

 

缺点很明显:Using temporary; Using filesort

 

[sql] 

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   

 

第二种是联合查询

[sql] 

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`  

)  

第三种是子查询

 

窃以为第二种效率最高
 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template