【发布时间】:2020-07-19 14:10:41
【问题描述】:
我有一个包含 3 个表问题、答案、评论的数据库,它按预期工作,每个问题可以有多个答案,每个答案可以有多个评论
create table Question(
questionId int primary key auto_increment,
title varchar(34) not null,
content TEXT not null
);
create table Answer(
answerId int primary key auto_increment,
questionId int not null,
content TEXT not null
);
create table Comment(
commentId int primary key auto_increment,
answerId int,
questionId int,
content TEXT not null
);
insert into Question(title, content) values('Testing Question','Testing Question');
insert into Answer(questionId, content) values(1,'Testing Answer 1');
insert into Answer(questionId, content) values(1,'Testing Answer 2');
insert into Comment(answerId, questionId, content) values(1, 1,'Testing Comment 1 to Answer 1');
insert into Comment(answerId, questionId, content) values(1, 1,'Testing Comment 2 to Answer 1');
insert into Comment(answerId, questionId, content) values(2, 1,'Testing Comment 1 to Answer 2');
insert into Comment(answerId, questionId, content) values(2, 1,'Testing Comment 2 to Answer 2');
我希望当我查询一个答案及其 cmets 时,我会在一个 List 中获得这些 cmets,例如:
[
{ answerId: 1, answerContent: 'Answer Content', comments[...]},
{ answerId: 2, answerContent: 'Answer Content', comments[...]}
]
这可能吗?我曾尝试使用此查询:
select * from Answer inner join Comment on Comment.answerId = Answer.answerId where Comment.questionId = 1;
显然它给了我这个:
[
{
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Answer 1",
"commentId" : 1,
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Comment 1 to Answer 1"
},
{
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Answer 1",
"commentId" : 2,
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Comment 2 to Answer 1"
},
{
"answerId" : 2,
"questionId" : 1,
"content" : "Testing Answer 2",
"commentId" : 3,
"answerId" : 2,
"questionId" : 1,
"content" : "Testing Comment 1 to Answer 2"
},
{
"answerId" : 2,
"questionId" : 1,
"content" : "Testing Answer 2",
"commentId" : 4,
"answerId" : 2,
"questionId" : 1,
"content" : "Testing Comment 2 to Answer 2"
}
]
我也尝试过在上一个查询中使用 group by,如下所示:
select * from Answer inner join Comment on Comment.answerId = Answer.answerId where Comment.questionId = 1 group by Comment.questionId;
它还给了我这个:
[
{
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Answer 1",
"commentId" : 1,
"answerId" : 1,
"questionId" : 1,
"content" : "Testing Comment 1 to Answer 1"
}
]
【问题讨论】: