使用sum,count,group by和多个left连接MySQL执行查询

时间:2015-01-10 11:10:13

标签: mysql

我有三个表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`

votings table![][2]

用户表有三个字段,如user_id,first_name,username。 预期结果。

  1. 对它的提问是,没有选票和总票数。离。
  2. This is my result

    但有时候一些问题没有显示出来。

1 个答案:

答案 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