从联接表中仅获取3行

时间:2019-09-02 10:41:33

标签: mysql sql

我试图从联接表中仅获取三行。 例如,我有一个类别表。我想从这些类别中获取热门类别和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'

2 个答案:

答案 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