create table users
(
userId int auto_increment primary key,
username varchar(100) not null,
email varchar (100) not null
);
create table questions
(
qId int auto_increment primary key,
topicId varchar(50) not null,
userId int not null,
question varchar(1000) not null
);
create table answers
(
aId int auto_increment primary key,
qId int not null,
answer varchar(1000) not null
);
insert users (username,email) values ('sparky','sp@me.com'),('sarah','sarah@me.com');
truncate table questions; -- for debugging
insert questions (topicId,userId,question) values ('0d3fb89c012b5af12e1e0',1,'Does life exist outside our galaxy?');
insert questions (topicId,userId,question) values ('0d3fb89c012b5af12e1e0',1,'Are fish really that dumb? Really?');
insert questions (topicId,userId,question) values ('xxxxxx',1,'Am I here?');
insert questions (topicId,userId,question) values ('xxxxxx',1,'Am you here?');
truncate table answers; -- for debugging
insert answers (qId,answer) values (1,'I hope so.');
insert answers (qId,answer) values (1,'I think so.');
insert answers (qId,answer) values (2,'What is wrong with you.');
insert answers (qId,answer) values (2,'Fish are nice.');
insert answers (qId,answer) values (2,'I like turtles.');
insert answers (qId,answer) values (3,'I like turtles too.');
insert answers (qId,answer) values (3,'Me 3.');
-- select * from users;
-- select * from questions;
-- select * from answers;
select
q.qId,u.username,q.question,u.email,count(a.aId) as AnswerCount
from users u
join questions q
on q.userId=u.userId and q.topicId='0d3fb89c012b5af12e1e0'
join answers a
on a.qId=q.qId
group by q.qId,u.username,q.question,u.email
+-----+----------+-------------------------------------+-----------+-------------+
| qId | username | question | email | AnswerCount |
+-----+----------+-------------------------------------+-----------+-------------+
| 1 | sparky | Does life exist outside our galaxy? | sp@me.com | 2 |
| 2 | sparky | Are fish really that dumb? Really? | sp@me.com | 3 |
+-----+----------+-------------------------------------+-----------+-------------+
2 rows in set (0.04 sec)