0

我需要帮助限制此查询的结果集。

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

当前返回下面的数组。

在此处输入图像描述

但是,我需要在具有我指定的 ID 的行之后找到列表中的行,记住这些将根据 ORDER BY tt.sticky DESC、pp.time DESC 更改订单。此外,行永远不会是完美的 ID 顺序,因此基于 ID 字段是不可能的。

例如,如果我想查找 ID = 24 之后的下一行,则查询结果将是 ID => 23

4

2 回答 2

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,但无论如何它都应该有效。

于 2012-11-23T17:49:28.790 回答
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

这可以重写为单个查询。上面的查询没有优化,但会给出你需要的结果。我会再想一想并尝试发布优化的查询。

于 2012-11-22T05:40:56.397 回答