我有以下查询,如果级别只有1级深度,那么效果很好,但是如果有更多级别,则查询会导致问题,因为它不会显示嵌套级别
SELECT
question.question,
answer.answer,
answer.questionid,
answer.pid,
question.DateAdded,
answer.DateAdded
FROM
answer
RIGHT JOIN question ON answer.questionid = question.id
请指导我如何处理
我的表结构是这样的:
问题表:id
question
DateAdded
答案表:
pid
answer
questionid
DateAdded
按嵌套级别表示使用答案表的pid
将条目插入答案表并插入questionid
字段
答案 0 :(得分:0)
我们假设你有以下带有伪代码服务器语言的html标记。
Question:<br/>
{{question.question}}<br/>
Answers:<br/>
<ul>
{{foreach answer in getRootAnswers(question.id)}}
<li>{{printAnswer(answer)}}</li>
{{/foreach}}
</ul>
getRootAnswers(questionId)
函数将返回pid
为空的顶级答案。它应该生成像
SELECT
answer,
id,
DateAdded
FROM answer
WHERE questionid = @questionId AND pid is null
ORDER BY DateAdded
printAnswer
将生成标记
Added on: {{answer.DateAdded}}<br/>
{{answer.answer}}<br/>
<ul>
{{foreach childAnswer in getChildAnswers(answer.id)}}
<li>{{printAnswer(childAnswer)}}</li>
{{/foreach}}
<ul>
标记将首先打印answer
信息。然后它将打印answer
的子答案。请注意printAnswer
递归调用。
getChildAnswers(parentId)
函数会返回一个孩子回答parentId
标识的答案。它应该生成像
SELECT
answer,
id,
DateAdded
FROM answer
WHERE pid = @parentId
ORDER BY DateAdded
您最终对答案树中的每个节点都有一个查询。