数据库中每个数据的类别由特定的 id 并且只允许为每个类别 mysql 获取 2
Posted
技术标签:
【中文标题】数据库中每个数据的类别由特定的 id 并且只允许为每个类别 mysql 获取 2【英文标题】:categories for each data in database by a specific id and only allow get 2 for each categories mysql 【发布时间】: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 |
+-------+----------+-------------+
我希望查询这样做有什么想法吗?
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于数据库中每个数据的类别由特定的 id 并且只允许为每个类别 mysql 获取 2的主要内容,如果未能解决你的问题,请参考以下文章