mysql 从表中获取每个类别的最新文章

标签 mysql

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

我有两张像这样简单的 table

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

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

网站上的结果是这样的

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 查询以获得相同的结果。

非常感谢。

最佳答案

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

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

关于mysql 从表中获取每个类别的最新文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628047/

相关文章:

php - MySQL数据库无法识别从Excel文件(xls)中提取的汉字

mysql - SQLSTATE[23000] : Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' , 查询为:INSERT INTO `log_visitor`

MySQL Inner Join 改变记录顺序

Mysql查询逻辑从数据库列出卖家

mysql - 正则表达式模式相当于 mysql 中的 %word%

mysql - sql 中的右侧 Alt 移位

mysql - 在嵌套选择中使用父查询的结果

php - 从mysql数据库中检索记录

c# - XmlRpc 调用未到达 MySql 服务器

javascript - 使用多页的选择选项标记从 mysql 中排序数据