0
________________________________
|oc_ct_forum_reply              |
--------------------------------|
| forum_reply_id | forum_post_id|
|-------------------------------|
|  21            |  25          |
|  22            |  25          |
|  25            |  25          |
|  28            |  25          |
---------------------------------

我有一个名为oc_ct_forum_reply尝试forum_reply_id使用以下 sql 查询查找第一个表的表:

  SELECT forum_reply_id
    FROM oc_ct_forum_reply
   WHERE forum_post_id = 25
ORDER BY reply_added
   LIMIT 1
       ;

我使用另一个来获取 forum_post_id 的回复总数:

  SELECT COUNT(*) AS total
    FROM oc_ct_forum_reply
   WHERE forum_post_id = 25
       ;

我需要一个 sql 查询,它给我一个给定在属于给定forum_reply_id的排序s 中的位置。假设我提供25 和25,我希望查询作为其第三个条目返回,或者说我提供25 和28 的 a,我希望将值作为其第四个条目。我已经使用上面的两个查询尝试了各种组合。forum_reply_idforum_post_idforum_post_idforum_reply_id3forum_post_idforum_reply_id4

4

2 回答 2

4

这应该工作

SELECT 
  t1.forum_reply_id,
  count(t2.forum_reply_id) as reply_number
FROM
  oc_ct_forum_reply t1
  JOIN oc_ct_forum_reply t2 ON ( t1.forum_reply_id >= t2.forum_reply_id AND t1.forum_post_id = t2.forum_post_id )
WHERE
  t1.forum_reply_id = 25
  AND t1.forum_post_id = 25
GROUP BY
  t1.forum_reply_id 

SQLFIDDLE

在职的

  1. oc_ct_forum_reply t1得到具有的行forum_reply_id = 25 AND t1.forum_post_id = 25

  2. 然后,我做了一个SELF JOIN来获取当前的reply_id的编号 (通过获取所有forum_reply_id小于或等于当前t1.forum_reply_id并且具有相同forum_post_id的行t1 然后将它们分组

上述动作 fetch 3 rows,如

t1.forum_reply_id , t2.forum_reply_id 
-----------------------------
 25               , 21                
 25               , 22                
 25               , 25                

最后,我只是GROUP BY t1.forum_reply_id使用COUNT()聚合函数来显示total rows请求的礼物forum_reply_id( 25 )

于 2013-04-19T18:12:31.930 回答
0

替代:

SELECT rownum FROM
(
SELECT @rownum:=@rownum+1 rownum, oc_ct_forum_reply.* 
FROM (SELECT @rownum:=0) r, oc_ct_forum_reply
) result_table
WHERE FORUM_REPLY_ID = 25;

http://sqlfiddle.com/#!2/5df2f/29

于 2013-04-19T18:42:50.513 回答