我有以下表格结构:
分类 id,name,limit
帖子: id,类别,标题,正文,日期,作者
我要做的是显示类别表格中“限制”字段限制的每个类别的最新帖子,按帖子日期排序。
答案 0 :(得分:0)
如果我理解你:
SELECT * FROM posts LEFT JOIN Category ON posts.category = Category.id WHERE limit = 'some limit' ORDER BY category, date DESC
(假设:posts.category是类别表主键的引用)
答案 1 :(得分:0)
尝试这样的事情:(不测试错误)
$result = mysql_fetch_array(mysql_query("<query to select your category>"));
$limit = $result['limit'];
$queryResult = mysql_query("select * from posts order by date desc limit $limit");
//do whatever you want with the $queryResult
答案 2 :(得分:0)
N-Greatest-Per-Group的有趣变化
SELECT id, name, limit, postid, title, body, date, author
FROM
(
SELECT
c.id, c.name, c.limit, p.id postid, p.title, p.body, p.date, p.author
@r:=case when @g=C.id then @r+1 else 1 end r,
@g:=C.id
FROM
(select @g:=null,@r:=0) n
CROSS JOIN CATEGORY C
INNER JOIN POSTS p on p.category = c.id
ORDER BY
C.ID, postid
) X
WHERE r<=c.limit
ORDER BY ID, postid
影响变量的一方基本上产生了2列
这可能很昂贵,因为没有快捷方式,它会在类别/帖子JOIN中为每一行编号,只有在此之后才会在WHERE r<=c.limit
位中减少。