今天以前的同學問我關於這方面的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`
)
第三種是子查詢
竊以為第二種效率最高