我有下表。
id | car_name | owner
-------------------------
1 | Toyota | Jan
2 | Ford | Mike
3 | Isuzu | Andrew
4 | BMW | Jan
5 | Ferrari | Steve
6 | Audi | Jan
7 | Benz | Kin
8 | Hyundai | Jan
9 | Kia | Jan
我想得到所有车主,但如果Jan有5辆或更多车,我可以修改查询并将Jan的前四项列入列表。我不关心我收到剩余物品的订单。我的首要任务是Jan应该是第一个。
id | car_name | owner
-------------------------
1 | Toyota | Jan
4 | BMW | Jan
7 | Benz | Jan
8 | Hyundai | Jan
2 | Ford | Mike
3 | Isuzu | Andrew
5 | Ferrari | Steve
6 | Audi | Bob
答案 0 :(得分:0)
我认为你需要枚举值,变量是最简单的方法。然后,额外的连接将为您提供按表中最常用的名称订购的信息:
select t.*
from (select t.*,
(@rn := if(@n = name, @rn + 1,
if(@rn := name, 1, 1)
)
) as rn
from t cross join
(select @n := '', @rn := 0
order by name
) t join
(select name, count(*) as cnt
from t
group by name
) tn
on t.name = tn.name
where rn <= 4
order by cnt desc, name;