【问题标题】:categories for each data in database by a specific id and only allow get 2 for each categories mysql数据库中每个数据的类别由特定的 id 并且只允许为每个类别 mysql 获取 2
【发布时间】:2014-12-06 08:44:19
【问题描述】:

可能重复MySql Query: Select top 3 rows from table for each category。我不清楚为什么我又问了一个答案。

这是我的数据库

+-------+----------+-------------+
|  id   |  app_Id  |   Content   |
+-------+----------+-------------+
|   1   |    19    | Hello Peer  |
+-------+----------+-------------+
|   2   |    20    | Hello Peer  |
+-------+----------+-------------+
|   3   |    19    | Hello Peer  |
+-------+----------+-------------+
|   4   |    19    | Hello Peer  |
+-------+----------+-------------+
|   5   |    21    | Hello Peer  |
+-------+----------+-------------+
|   6   |    20    | Hello Peer  |
+-------+----------+-------------+
|   7   |    19    | Hello Peer  |
+-------+----------+-------------+
|   8   |    20    | Hello Peer  |
+-------+----------+-------------+
|   9   |    21    | Hello Peer  |
+-------+----------+-------------+

现在如何按 app_Id 选择记录类别,每个类别限制为 2 并按 appId desc 排序

如果上面的陈述不清楚。这是我预期的上面数据库的输出记录。

+-------+----------+-------------+
|  id   |  app_Id  |   Content   |
+-------+----------+-------------+
|   4   |    19    | Hello Peer  |
+-------+----------+-------------+
|   7   |    19    | Hello Peer  |
+-------+----------+-------------+
|   6   |    20    | Hello Peer  |
+-------+----------+-------------+
|   8   |    20    | Hello Peer  |
+-------+----------+-------------+
|   5   |    21    | Hello Peer  |
+-------+----------+-------------+
|   9   |    21    | Hello Peer  |
+-------+----------+-------------+

我希望查询这样做有什么想法吗?

【问题讨论】:

    标签: mysql sql select sql-order-by greatest-n-per-group


    【解决方案1】:

    试试这个:

    SELECT id, app_Id, Content 
    FROM (SELECT id, app_Id, Content, 
                 IF(@appId=@appId:=app_Id, @rowNo:=@rowNo+1, @rowNo:=1) AS rowNo 
          FROM tableA, (SELECT @rowNo:=1, @appId:=0) a
          ORDER BY app_Id, id DESC
         ) AS a 
    WHERE rowNo <= 2
    ORDER BY app_Id
    

    【讨论】:

      【解决方案2】:

      您可以使用更简单的版本获得所需的结果

      select c.* from category c
      where
      (
        select count(*) from category as c1
        where c.app_Id = c1.app_Id
        and c.id < c1.id
      )<=1
      order by c.app_Id;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 2021-10-04
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多