Mysql选择限制为不同列的行

时间:2016-05-30 11:44:52

标签: mysql

表的结构如下所示

Posts (
   id int, 
   category_id int, 
   popularity int, 
)

我想选择5个类别,每个类别有5行。

喜欢选择*来自其中category_id的帖子(" 1"," 2"," 3"," 4",&# 34; 5")限制5 - 通过选择5来限制每个category_id

1 个答案:

答案 0 :(得分:1)

使用UNION连接多个select语句以显示一个组合结果 这可能是解决问题的最简单方法。

像这样:

SELECT * FROM posts where category_id=1 limit 5
UNION 
SELECT * FROM posts where category_id=2 limit 5
UNION 
SELECT * FROM posts where category_id=3 limit 5
UNION 
SELECT * FROM posts where category_id=4 limit 5
UNION 
SELECT * FROM posts where category_id=5 limit 5

已经提出同样的问题: MySQL: Limiting number of results received based on a column value | Combining queries 它提供了更复杂的解决方案。