gpt4 book ai didi

mysql - 从联接表中仅获取 3 行

转载 作者:行者123 更新时间:2023-11-29 02:38:48 24 4
gpt4 key购买 nike

我试图从联接表中只获取三行。例如,我有一个类别表。我想在不使用 SQL inside 循环的情况下从这些类别中获取热门类别和 3 篇文章。帖子总数应为 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'

最佳答案

在 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

关于mysql - 从联接表中仅获取 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57755540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com