[英]MySQL query (joining tables)
QuestionsTable 问题表
id* (int) | id *(int)| question_text (string) |
问题文本(字符串)| question_type (int)
question_type(int)
AlternativesTable 替代表
id* (int) | id *(int)| question_id (int) |
question_id(int)| alternative_text (string) |
Alternative_text(字符串)| is_correct (bool)
is_correct(布尔)
AnswersTable 答案表
id* (int) | id *(int)| question_id (int) |
question_id(int)| alternative_id (int) |
Alternative_id(int)| answer_text (string)
answer_text(字符串)
" * " = primary key “ *” =主键
Every question can either be of type free text or multiple selector. 每个问题可以是自由文本类型,也可以是多个选择器。 A multiple selector question has one or more alternatives and only one can be correct.
多重选择器问题有一个或多个选择,只有一个是正确的。
An answer is defined by a question_id and an alternative_id (multiple selector) or an answer_text (free text). 答案由question_id和alternate_id(多个选择器)或answer_text(自由文本)定义。 The is_correct bool is so I can mark which answer is the correct one.
is_correct bool是,所以我可以标记哪个答案是正确的。
How do I make an SQL query that will give me all the alternatives listed for every question with a count on each alternative that shows how many has selected it? 如何进行SQL查询,为我提供每个问题列出的所有替代方案,并统计每个替代方案的数量,以显示选择了多少替代方案? Say I can store it in an array and iterate through it with an foreach-loop and show it as the example below.
假设我可以将其存储在数组中,并使用foreach循环对其进行遍历,并将其显示为以下示例。
An example, every question is represented by it's question_text, and every alternative beloning to that question is represented by Alt1 (alternative_text), Alt2, and so on... The numbers after the alternatives is the number of selections it got (answers). 例如,每个问题都由question_text表示,与该问题相关的每个替代项都由Alt1(alternative_text),Alt2等表示。。。替代项后的数字是它得到的选择数(答案)。
Alt1 | Alt1 | 3
3
Alt2 | Alt2 | 2
2
Alt3 | Alt3 | 0
0
Alt1 | Alt1 | 2
2
Alt2 | Alt2 | 3
3
Answer1 答1
Answer2 答2
.... ....
I can make the query that gives me all questions and all the alternatives that belong to it, but I fail when I try to get the count on all answers for every question alternative. 我可以查询所有问题以及属于它的所有替代方法,但是当我尝试获取每个问题替代方法的所有答案时,我就失败了。
So now I could use some help from a SQL-ninja =) 所以现在我可以使用来自SQL-ninja的一些帮助=)
Thanks in advance Daniel 在此先感谢Daniel
Off the top of my head, this might work: 在我的头顶上,这可能起作用:
SELECT alternatives.id, COUNT(DISTINCT(answers.id))
FROM alternatives
LEFT JOIN answers ON alternatives.id = answers.altid
GROUP BY alternatives.id;
That should give you the total number of times each alternative occurs in the answers
table. 这样可以为您提供
answers
表中每种替代方法出现的总次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.