我需要帮助限制此查询的结果集。
SELECT tt.id
FROM kf_topics AS tt
LEFT JOIN kf_posts AS pp
ON tt.id = pp.topicid
WHERE tt.boardid = 1
GROUP BY tt.id
ORDER BY tt.sticky DESC, pp.time DESC
Current返回下面的数组。
但是,我需要在具有我指定ID的行之后的列表中找到行,请记住这些行将根据ORDER BY tt.sticky DESC,pp.time DESC更改命令ALOT。此外,行永远不会处于完美的ID顺序,因此将其置于ID字段上是不可能的。
例如,如果我想在ID = 24之后找到下一行,则查询结果将是ID => 23
答案 0 :(得分:3)
我们可以使用单个查询执行此操作,如下所示
SELECT ttid
FROM
(SELECT tt.id ttid,@row:=@row+1 rownum,IF(tt.id=24,@j:=@row,0)
FROM kf_topics AS tt
LEFT JOIN kf_posts AS pp
ON tt.id = pp.topicid JOIN (SELECT @row:=0) AS rowcount
WHERE tt.boardid = 1
GROUP BY tt.id
ORDER BY tt.sticky DESC, pp.time DESC) A JOIN (SELECT @j+1 as rownum) B ON (A.rownum=B.rownum);
我不确定你为什么使用group by,但它无论如何都应该有用。
答案 1 :(得分:0)
SET @row:=0;
SELECT rownum+1 INTO @nextrow FROM
(SELECT tt.id AS id, @row AS rownum
FROM kf_topics AS tt
LEFT JOIN kf_posts AS pp
ON tt.id = pp.topicid
WHERE tt.boardid = 1
AND (@row:=@row+1)<=1
GROUP BY tt.id
ORDER BY tt.sticky DESC, pp.time DESC) A
WHERE A.id=<id>)
SET @row=0;
SELECT A.id FROM
(SELECT tt.id AS id, @row AS rownum
FROM kf_topics AS tt
LEFT JOIN kf_posts AS pp
ON tt.id = pp.topicid
WHERE tt.boardid = 1
AND (@row:=@row+1)<=1
GROUP BY tt.id
ORDER BY tt.sticky DESC, pp.time DESC) A
WHERE A.rownum=@nextrow
这可以重写为单个查询。上述查询未进行优化,但会提供您需要的结果。我会再考虑并尝试发布opmized查询。