我有以下sql语句:
SELECT e.comment_id AS parentcomment,
m.comment_id AS child_id
FROM comments e
INNER JOIN comments m
ON e.comment_id=m.parent_id
WHERE e.parent='1' AND e.parent_id='$parentid' AND m.parent='0';
示例输出:
+---------------+----------+
| parentcomment | child_id |
+---------------+----------+
| 1 | 3 |
| 1 | 4 |
| 1 | 7 |
| 5 | 8 |
| 1 | 9 |
| 1 | 10 |
| 1 | 11 |
| 1 | 12 |
| 1 | 13 |
| 1 | 14 |
| 1 | 15 |
| 1 | 16 |
| 1 | 17 |
| 1 | 18 |
| 1 | 19 |
| 1 | 20 |
| 1 | 21 |
| 1 | 22 |
| 1 | 23 |
| 1 | 24 |
| 1 | 25 |
| 26 | 32 |
| 26 | 33 |
| 27 | 34 |
| 27 | 35 |
| 28 | 36 |
| 29 | 37 |
| 30 | 38 |
| 31 | 39 |
| 26 | 40 |
+---------------+----------+
30 rows in set
我想做什么 - 我只想为每个child_id
值显示15个parentcomment
值。除此之外,我只想要检索30个parentcomment
值。
此外,我希望通过某个索引ORDER
parentcomment
值(让我们说id
)并选出前30名,然后选出前15名有序的child_id
值(也按id
排序)。
希望这是有道理的。我该怎么办?
提前致谢。
答案 0 :(得分:1)
你应该可以使用这个(sqlFiddle)这里我只抓取3(而不是15)child_id和6(而不是30)parentcomment
在我的示例中,$parentid
为1
。最里面的查询是您刚添加ORDER BY parentcomment,child_id
SELECT parentcomment,child_id,parentRank,childRank
FROM
(SELECT parentcomment,
child_id,
IF (@prevparent <> parentcomment, @parentRank:=@parentRank+1, @parentRank) as parentRank,
IF (@prevparent <> parentcomment, @childRank:=1, @childRank:=@childRank+1) as childRank,
@prevparent := parentcomment
FROM
(SELECT e.comment_id AS parentcomment,
m.comment_id AS child_id
FROM comments e
INNER JOIN comments m
ON e.comment_id=m.parent_id
WHERE e.parent='1' AND e.parent_id='1' AND m.parent='0'
ORDER BY parentcomment,child_id
)T1,
(SELECT @prevparent:=0,@parentRank:=0,@childRank:=0)rank
)T2
WHERE parentRank BETWEEN 1 AND 6
AND childRank BETWEEN 1 AND 3