我有一个电子商务表“订单”,表中有'状态'记录和'水果'记录。我试图(和失败)创建一个查询,将返回每个州的结果和前3个最受欢迎的水果,按顺序显示。带嵌套列表的MySQL查询
所以, '订单' 表看起来像这样:
id State Fruit
----------------
1 CA grape
2 FL orange
3 CA grape
4 FL grapefruit
5 CA orange
6 CA grape
7 FL orange
8 CA peach
9 CA orange
10 FL orange
11 FL grapefruit
12 FL peach
etc etc etc
在此表上查询的结果将是:
the_state the_fruits
------------------------
CA grape, orange, peach
FL orange, grapefruit, peach
我尝试这样做:
SELECT state as the_state,
(select count(id) as count, fruit from orders where state = the_state order by count(id) limit 3 ) as the_fruits
FROM orders
group by fruit
order by count(id) DESC
但是,这是无效的有效查询,我不知道我在正确的轨道上
我的表实际上有很多的水果,这查询不返回顶部3.返回随机3.与国家,水果的表中的第一个查询,CF是正确的。 – lilbiscuit 2014-10-06 13:03:52
我更新了group_concat函数,以排列前3名,按水果名排序的关系。让我知道这个是否奏效。 – 2014-10-08 22:50:39