我有一個電子商務表「訂單」,表中有'狀態'記錄和'水果'記錄。我試圖(和失敗)創建一個查詢,將返回每個州的結果和前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