mysql - 如何为每个类别选择准确数量的文章?

标签 mysql sql

这是我的表格:

CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `post_limit` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

INSERT INTO `category` (`id`, `title`, `post_limit`) VALUES
(1, 'News', 2),
(2, 'Sport', 2),
(3, 'Science', 1),
(4, 'Games', 1);

CREATE TABLE IF NOT EXISTS `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `category_id` (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;

INSERT INTO `article` (`id`, `title`, `category_id`) VALUES
(1, 'news article 1', 1),
(2, 'news article 2', 1),
(3, 'news article 3', 1),
(4, 'sports article 1', 2),
(5, 'sports article 2', 2),
(6, 'sports article 3', 2),
(7, 'Science article 1', 3),
(8, 'Science article 2', 3),
(9, 'games article 1', 4),
(10, 'games article 2', 4);

我需要做的是选择 10 篇文章 (ORDER BY article.id DESC) 但要记住每个类别都有 post_limit,所以例如我们不能对于 category_id=1 5 个帖子,如果 post_limit=2

提前谢谢你。

更新 1: 结果应该是:

10  games article 2     4
8   science article 2   3
6   sports article 3    2
5   sports article 2    2
3   news article 3      1

最佳答案

将每个类别的计数限制为该类别的post_limit:

select c.id, c.title, least(post_limit, count(a.id))
from category c
left join article a on category_id = c.id
group by 1, 2 -- or "group by c.id, c.title" if you prefer the verbose style

参见 SQLFiddle .

关于mysql - 如何为每个类别选择准确数量的文章?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240788/

相关文章:

sql - SQL Server 2000 中的多参数搜索

sql - PLPGSQL 中的 BLOB 到图像转换

mysql - JOIN 返回表中的所有数据

php - SQL 选择查询内存问题

php - insert语句不将记录插入数据库

MySql 按小时查询

mysql - SQL 结果的随机样本

mysql - 将相似的项目分组

非唯一列上的 SQL Server 聚集索引

删除大表中的记录时MySQL很慢