[英]Get only 3 rows from joined table
I'm trying to get only three rows from the joined table.我试图从连接表中只获取三行。 For example, I have a categories table.
例如,我有一个类别表。 I want to get popular categories and 3 articles from these categories without using SQL inside loop.
我想在不使用 SQL 内部循环的情况下从这些类别中获取流行类别和 3 篇文章。 Total post count should be 12.
总帖子数应为 12。
I tried this but didn't work.我试过这个,但没有用。 (If I set
limit 1
it works. But not working on limit 3
) (如果我设置
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'
Your subquery returns multiple records (actually 3), so the equality operator should be replaced with the IN
operator.您的子查询返回多条记录(实际上是 3 条),因此应将相等运算符替换为
IN
运算符。
Consider:考虑:
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'
In MySQL 8+, you would simply do:在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.