【问题标题】:mysql get lastess articles from table with every categorymysql 从每个类别的表中获取最新文章
【发布时间】:2013-09-05 14:25:47
【问题描述】:

我在 http://www.xaluan.com 从事 tintuc 项目

我有两张这样简单的桌子

table articles
 ID - Title - Des - CatID
table category
 CatID - catTitle 

通常我会在类别表上运行循环以接收 CatID 和 catTile,然后在文章表上再次运行循环以使 4 篇最新文章属于该 CatID

这样的网站上的结果

catTitle 1 
 - lastes article belong to catID 1
 - second last artice belong to catID 1
catTitle 2
 - lastess article belong to catID 2
 - second last article belong to catID 2

我认为循环遍历类别表然后在文章表上为每个 catId 循环多次不是有效方式。

请帮助最有效的mysql查询以获得相同的结果。

非常感谢。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您无法以您提到的格式获得结果,但是,您可以运行此查询并循环遍历结果以格式化数据,使其看起来像上面显示的那样。

    SELECT c.catTitle, c.CatID, a.Title, a.ID , a.Des
    FROM category c, artices a
    WHERE c.CatID  = a.CatID 
    ORDER BY c.CatID ASC, a.ID DESC
    

    编辑:

    如果您只想要前 4 名,请使用此查询

    SELECT c.catTitle, c.CatID, a.Title, a.ID , a.Des
    FROM category c, (SELECT ID, Title, Des, CatID
    FROM
    (
       SELECT ID, Title, Des, CatID,
          @num := if(@CatID = `CatID`, @num + 1, 1) AS row_number,
          @CatID := `CatID` AS dummy
      FROM articles
      ORDER BY CatID, ID DESC
    ) AS x WHERE x.row_number <= 4) a
    WHERE c.CatID  = a.CatID
    ORDER BY c.CatID ASC, a.ID DESC
    

    demo

    【讨论】:

    • 谢谢,但这看起来并没有限制结果中每个 catid 的文章数。我只需要显示 4 篇文章,因此 3 个类别将有 12 行结果。
    • 谢谢.. 我刚刚用我们的数据测试了您的查询.. 大约 600000 行.. 花了很长时间,有一段时间超过了 sql 运行时的限制..
    • @BinhNguyen 您需要在列上建立索引来固定。像CatID 列。通常是您在WHEREJOIN 子句中经常使用的任何列。
    【解决方案2】:

    如果ID 是您的排序依据(我没有看到文章排序依据),则查询可以写成;

    SELECT a.* FROM articles a
    WHERE (
       SELECT COUNT(b.id) FROM articles b WHERE a.id < b.id AND a.CatID = b.CatID
    ) < 4;
    

    显示同一类别中新文章少于 4 篇的所有文章。

    An SQLfiddle to test with.

    【讨论】:

    • 感谢您提供非常短的查询,但也花费了很长时间......我们的数据有 600k 行数据......
    • @BinhNguyen 你的桌子上有索引吗? (特别是article.CatIDarticle.id)?
    • 是的,它们都有 articleid 和 catid 的索引列 .. .. 目前我必须回到旧的方式 .. 列出所有类别,然后逐一循环以从每个类别中获取最新的 4 篇文章。 .
    猜你喜欢
    • 2016-02-06
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多