带有嵌套列表的 MySQL 查询

标签 mysql

我有一个电子商务表“订单”,该表有一个“状态”记录和一个“水果”记录。我正在尝试(但失败了)创建一个查询,该查询将按顺序返回每个州的结果和前 3 名最受欢迎的水果。

所以“订单”表看起来像这样:

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

但这不是一个有效的查询,我不确定我是否在正确的轨道上

最佳答案

在MySQL中限制分组数据的结果是相当困难的。各种线程上有许多解决方案,但这可能在很大程度上取决于您拥有的数据类型和数量。

以下可能是最简单的解决方案。

mysql> INSERT INTO orders VALUES
    -> ('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'),
    -> ('13', 'CA', 'apple'),
    -> ('14', 'FL', 'apple');
Query OK, 14 rows affected (0.03 sec)
Records: 14  Duplicates: 0  Warnings: 0

mysql> select state, fruit, count(fruit) cf from orders group by state, fruit order by state, cf desc;
+-------+------------+----+
| state | fruit      | cf |
+-------+------------+----+
| CA    | grape      |  3 |
| CA    | orange     |  2 |
| CA    | peach      |  1 |
| CA    | apple      |  1 |
| FL    | orange     |  3 |
| FL    | grapefruit |  2 |
| FL    | peach      |  1 |
| FL    | apple      |  1 |
+-------+------------+----+
8 rows in set (0.00 sec)

SELECT state
     , SUBSTRING_INDEX(GROUP_CONCAT(fruit ORDER BY cf DESC, fruit),',',3) top3 
  FROM 
     ( SELECT state
            , fruit
            , COUNT(fruit) cf 
         FROM orders 
        GROUP
           BY state
            , fruit
     ) t1 
 GROUP 
    BY state;
+-------+-------------------------+
| state | top3                    |
+-------+-------------------------+
| CA    | grape,orange,peach      |
| FL    | orange,grapefruit,apple |
+-------+-------------------------+
2 rows in set (0.00 sec)

关于带有嵌套列表的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26164863/

相关文章:

mysql - 分组最大值

mysql - 使用一组选择最佳方法的结果插入行

php - Cake PHP自动将id字段添加到sql查询中

php - 以base64格式对图像进行编码并存储在mysql数据库中,不适用于php和laravel的所有类型的图像

Mysql - 当嵌套选择查询是动态时,Not In 需要时间,但如果它是常量,则不需要时间

mysql - 我需要从 3 个分类法(个人资料类别、县、部门)获取帖子数据

php - 从 mysql 数据库检索文本

mysql - 按另一个相关模型属性排序 - Ruby on Rails

mysql - 如何使用 group by 子句对数据透视表 (MySQL) 中的列值进行小计

php - 从数据库中搜索关键字