mysql 查询所有评论以及回复
高洛峰
高洛峰 2017-04-17 15:30:30
0
2
721

表设计如下

question(id, user_id,content)
answer (id,question_id,user_id,content)
reply (id,answer_id, user_id,content)

请问要怎么一次性查询所有的评论和回复啊
目前用group by和group_concat实现不了额..

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
刘奇

I understand: question is a question table, listing all questions
answer is a reply table, a reply to a specific question, using question_id to associate with the id in the question table
reply is a reply to a certain question Comments, use answer_id to associate with the id in the answer table
The following code is based on the above understanding

select t1.q_id as 问题id
, t1.q_user_id as 提问者id
, t1.q_content as 问题内容
, t2.a_id as 回复id
, t2.a_user_id as 回复者id
, t2.a_content as 回复内容
, t3.r_id as 评论id
, t3.r_user_id as 评论者id
, t3.r_content as 评论内容
from 
(
select id as q_id ,user_id as q_user_id ,content as q_content
from question
) t1 -- 所有的问题列表,用id做唯一性的区分
left outer join
(
select id as a_id ,question_id ,user_id as a_user_id ,content as a_content
from answer
) t2
on t1.q_id = t2.question_id -- 每个question_id对应的回复
left  outer join
(
select id as r_id ,answer_id ,user_id as r_user_id ,content as r_content
) t3 
on t2.a_id = t3.answer_id -- 每个answer_id对应的评论
Peter_Zhu

select reply.,answer.,question.* from
reply
right join answer on
reply.answer_id = answer.I'd
right join question on
answer.question_id = question.id
Where question.id =(查找的question.id)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!