我有两张像这样简单的桌子
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查询得到相同的结果。
谢天谢地。答案 0 :(得分: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
答案 1 :(得分:0)
如果您正在排序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篇新文章的所有文章。