mysql 取每组前几条记录
1.用子查询:SELECT * FROM tableName a WHERE 3>(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND b.cnt>a.cnt)ORDER BY a.id,a.account DESC 2.用exists半连接:SELECT * FROM tableName a WHERE EXISTS(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND a.account<b.cnt HAVING COUNT(*)<3)ORDER BY a.id,a.cntDESC 二、同理可以取组内最小的N条记录:例如:取每组的前3条最小的记录1、子查询SELECT * FROM tableName a WHERE 3>(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND b.cnt<a.cnt)ORDER BY a.id,a.cnt DESC 2、用exists:SELECT * FROM tableName a WHERE EXISTS(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND a.cnt>b.cnt HAVING COUNT(*)<3)ORDER BY a.id,a.cnt DESC