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