【发布时间】:2009-02-07 03:47:03
【问题描述】:
我将尝试在另一个问题上更好地解释这一点。这是我认为应该可以工作的查询,但当然,MySQL 不支持这个特定的子选择查询:
select *
from articles a
where a.article_id in
(select f.article_id
from articles f
where f.category_id = a.category_id
order by f.is_sticky, f.published_at
limit 3) /* limit isn't allowed inside a IN subquery */
我要归档的是:在一个文章表中,我有几个类别的几篇文章。我需要为每个类别(任意数量的类别)获取最多三篇文章。
这是数据:
CREATE TABLE articles (
article_id int(10) unsigned NOT NULL AUTO_INCREMENT,
category_id int(10) unsigned NOT NULL,
title varchar(100) NOT NULL,
is_sticky boolean NOT NULL DEFAULT 0,
published_at datetime NOT NULL,
PRIMARY KEY (article_id)
);
INSERT INTO articles VALUES
(1, 1, 'foo', 0, '2009-02-06'),
(1, 1, 'bar', 0, '2009-02-07'),
(1, 1, 'baz', 0, '2009-02-08'),
(1, 1, 'qox', 1, '2009-02-09'),
(1, 2, 'foo', 0, '2009-02-06'),
(1, 2, 'bar', 0, '2009-02-07'),
(1, 2, 'baz', 0, '2009-02-08'),
(1, 2, 'qox', 1, '2009-02-09');
我要检索的是以下内容:
1, 1, qox, 1, 2009-02-09
1, 1, foo, 0, 2009-02-06
1, 1, bar, 0, 2009-02-07
1, 2, qox, 1, 2009-02-09
1, 2, foo, 0, 2009-02-06
1, 2, bar, 0, 2009-02-07
请注意“quox”是如何因为具有粘性而跃居该类别的首位。
你能想出一种方法来避免子查询中的 LIMIT 吗?
谢谢
【问题讨论】:
-
让我想起 MySQL 中何时不允许子查询
-
@Brettski,我相信他的意思是在查询中有一个限制。也许阅读他更新的问题?
-
IMO 正确的答案是“停止使用 MySQL”:) 这个查询在 PostgreSQL 中运行良好。