我试图从联接表中仅获取三行。 例如,我有一个类别表。我想从这些类别中获取热门类别和3篇文章,而无需在循环内使用SQL。帖子总数应为12。
我尝试了这个,但是没有用。 (如果我设置了limit 1
,它可以工作。但是不能在limit 3
上工作)
SELECT
categories.name AS cname,
categories.url AS curl,
articles.name,
articles.url,
articles.image
FROM
categories
JOIN articles ON articles.id = (
SELECT p.id
FROM articles AS p
WHERE categories.id = p.category AND p.delete = '0'
ORDER BY p.id DESC
LIMIT 3
)
WHERE
categories.delete = '0'
AND categories.popular = '1'
答案 0 :(得分:1)
您的子查询返回多个记录(实际上是3条),因此应将相等运算符替换为IN
运算符。
考虑:
SELECT
categories.name AS cname,
categories.url AS curl,
articles.name,
articles.url,
articles.image
FROM
categories
JOIN articles ON articles.id IN (
SELECT p.id
FROM articles AS p
WHERE categories.id = p.category AND p.delete = '0'
ORDER BY p.id DESC
LIMIT 3
)
WHERE
categories.delete = '0'
AND categories.popular = '1'
答案 1 :(得分:0)
在MySQL 8+中,您只需执行以下操作:
SELECT c.name AS cname, c.url AS curl,
a.name, a.url, a.image
FROM categories c JOIN
(SELECT a.*,
ROW_NUMBER() OVER (PARTITION BY a.category ORDER BY a.id DESC) as seqnum
FROM articles a
WHERE a.delete = 0
) a
ON a.category = c.id
WHERE a.seqnum <= 3 AND
c.delete = 0 AND
c.popular = 1