简体   繁体   English

左连接,分组和计数所需的数组

[英]Left join, group by and count for a needed array

I have questions, answers, question_type and possible_answers tables. 我有问题,答案,question_type和possible_answers表。 A question has a lot of answers which can be, in example, 1-5 stored in possible_answers table and related through the question_type table and questions table. 一个问题有很多答案,例如,1-5可以存储在possible_answers表中,并通过question_type表和问题表相关。

I usually solve this making a sql that returns the possible answers and then in a for I look again of every for with more sql sentences... that takes a lot of time. 我通常会解决这个问题,制作一个返回可能答案的sql,然后在一个for中,我会再次查看每个更多的sql语句......这需要花费很多时间。 My idea is to make in a single sql an array with the count of the answers of a question that puts zero on the possible_answers that has no answers: 我的想法是在单个sql中创建一个数组,其中包含一个问题答案的计数,该问题在没有答案的possible_answers上置零:

answer | count

1 | 234  
2 | 123    
3 | 0    
4 | 0    
5 | 876    

Is it possible? 可能吗? thanks a lot! 非常感谢!

I am assuming that the answer table contains a foreign key questionID. 我假设答案表包含外键questionID。 I will also assume that the question type is unnecessary to join them, but acts as a lookup table. 我还假设问题类型不必加入它们,但充当查找表。

If you want to populate a possible_answers table with the count of answers to questions, including zeros, try 如果要使用问题的答案计数填充possible_answers表,包括零,请尝试

INSERT INTO possible_answers
SELECT questions.questionID, COUNT(answers.answerID)
FROM questions
LEFT JOIN answers
ON questions.questionID = answers.questionID
GROUP BY questions.questionID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM