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`
)
第三種是子查詢
竊以為第二種效率最高