我有三个表1.user,2.project_questions,3.votings。
id project_id user_id question
1 593 308 Hello Question?
2 593 308 This is Another Question?
3 593 308 sdssds
4 593 308 asdsd
5 593 308 dsfdsfsdfsfsdfs
6 593 308 nro
7 593 308 dsfsdfsdfsdf
8 593 308 zxzx
9 593 308 zxzxasasasasasasasas
10 593 308 zxzxasasasasasasasasfdsfdsfdsfsdfdsfsdf
11 593 308 fdfdsf
12 593 308 saddsadsad
13 593 308 ghvhgvhg
这是我的疑问。
SELECT `project_questions`.*, count(votings.vote) as vote,
sum(case when votings.yes=1 then 1 else 0 end) as yes,
sum(case when votings.no=1 then 1 else 0 end) as no,
`user`.`image`, `user`.`user_name`, `user`.`last_name` FROM
(`project_questions`) LEFT JOIN `votings` ON
`votings`.`question_id`=`project_questions`.`id` LEFT JOIN `user` ON
`user`.`user_id`=`project_questions`.`user_id` WHERE
`project_questions`.`project_id` = '593' GROUP BY `votings`.`question_id`
用户表有三个字段,如user_id,first_name,username。 预期结果。
但有时候一些问题没有显示出来。
答案 0 :(得分:1)
在评论中确认的答案是在project_questions.id而不是votings.question_id上分组
SELECT
project_questions.*,
count(votings.vote) as vote,
sum(case when votings.yes=1 then 1 else 0 end) as yes,
sum(case when votings.no=1 then 1 else 0 end) as no,
user.first_name,
user.last_name
FROM
project_questions
LEFT JOIN votings ON votings.question_id=project_questions.id
LEFT JOIN user ON user.user_id=project_questions.user_id
WHERE project_questions.project_id = '593'
GROUP BY project_questions.id