好吧,我想计算并显示我的表(故事)的评论。它的结构是这样的:
id | type | post | parent
1 | story | bla bla bla | 0
2 | comment | text... | 1
3 | comment | text... | 1
4 | comment | text... | 3
5 | comment | other... | 1
如您所见,所有信息都在一张表中。
例如,在这种情况下,我需要显示“故事”并显示它有多少评论。
我必须列出它的层次结构。
是这样的:
ID. 1 - bla bla bla
Comments
|--ID. 2 text...
|--ID. 3 text...
...|--ID. 4. text.. (comment of ID 3)
|--ID. 5 other..
当 ID 等于故事时,我知道如何列出故事及其所有评论。但是我不知道我需要做什么来显示和计算其他与主要故事无关的内容。
最好的方法是什么?
非常感谢。
最佳答案
试试这个 sqlFiddle
SELECT root.id as rootid,
root.type as roottype,
root.post as rootpost,
child.id as childid,
child.type as childtype,
child.post as childpost,
NULL as grandchildid,
NULL as grandchildtype,
NULL as grandchildpost
FROM stories as root
INNER JOIN stories as child ON child.parent = root.id
WHERE root.parent = 0
AND root.id = 1
UNION
SELECT root.id as rootid,
root.type as roottype,
root.post as rootpost,
child.id as childid,
child.type as childtype,
child.post as childpost,
grandchild.id as grandchildid,
grandchild.type as grandchildtype,
grandchild.post as grandchildpost
FROM stories as root
INNER JOIN stories as child ON child.parent = root.id
INNER JOIN stories as grandchild ON grandchild.parent = child.id
WHERE root.parent = 0
AND root.id = 1
ORDER BY childid,grandchildid
然后如果你想要一些看起来像你上面在你的问题中给出的输出,你可以做这样的事情(sqlFiddle)
SELECT IF(grandchildid IS NULL,
CONCAT("--ID. ",childid," ",childpost),
CONCAT("...--ID. ",grandchildid," ",grandchildpost,"(comment of ID ",childid,")")
) as result
FROM
(
SELECT root.id as rootid,
root.type as roottype,
root.post as rootpost,
child.id as childid,
child.type as childtype,
child.post as childpost,
NULL as grandchildid,
NULL as grandchildtype,
NULL as grandchildpost
FROM stories as root
INNER JOIN stories as child ON child.parent = root.id
WHERE root.parent = 0
AND root.id = 1
UNION
SELECT root.id as rootid,
root.type as roottype,
root.post as rootpost,
child.id as childid,
child.type as childtype,
child.post as childpost,
grandchild.id as grandchildid,
grandchild.type as grandchildtype,
grandchild.post as grandchildpost
FROM stories as root
INNER JOIN stories as child ON child.parent = root.id
INNER JOIN stories as grandchild ON grandchild.parent = child.id
WHERE root.parent = 0
AND root.id = 1
ORDER BY childid,grandchildid
)T1
如果你要允许多层次深度,你可以创建一个像这样的函数 sqlFiddle
CREATE FUNCTION getRootId(in_id int) returns int
BEGIN
DECLARE _parent int;
DECLARE _id int;
SET _parent = in_id;
SET _id = in_id;
WHILE (_parent != 0) DO
SELECT id,parent into _id,_parent
FROM stories WHERE id = _parent;
END WHILE;
RETURN _id;
END//
然后使用它来获取所有共享 root id 的评论,如下所示
SELECT parent.id as parentId,
parent.type as parentType,
parent.post as parentPost,
child.id as childId,
child.type as childType,
child.post as childPost,
getRootId(child.id) as rootId
FROM stories parent
INNER JOIN stories child ON (child.parent = parent.id)
WHERE getRootId(child.id) = 1
关于mysql - 如何从 MySQL 表中获取所有评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20795922/