查询以从每个问题的答案集中选择已回答所有问题的用户
这是mysql表。
User Question Answer
20 1 answer1_2
20 2 answer2_5
20 3 answer3_1
726 1 answer1_2
726 2 answer2_5
726 3 answer3_1
我希望用户回答了所有问题并且 我们为每个问题预定义了一组答案。
就像问题1可以从answer1_1、answer1_2、answer1_3中得到答案 问题2可以从answer2_1、answer2_2、answer2_3得到答案
最初,我尝试了这样的查询:
SELECT GROUP_CONCAT( DISTINCT CAST( User AS CHAR ) ) allUsers, COUNT( DISTINCT User ) totalUsers
FROM survey
WHERE
(
(
Question =1
AND Answer = 'answer1_2'
)
OR (
Question =1
AND Answer = 'answer1_2'
)
OR (
Question =1
AND Answer = 'answer1_3'
)
)
AND (
(
Question =2
AND Answer = 'answer2_1'
)
OR (
Question =2
AND Answer = 'answer2_2'
)
OR (
Question =2
AND Answer = 'answer2_3'
)
)
但后来我看到结果并意识到所有问题中的“AND”不能满足我的要求 但我需要这个逻辑的结果。
表结构无法更改。
This is mysql table.
User Question Answer
20 1 answer1_2
20 2 answer2_5
20 3 answer3_1
726 1 answer1_2
726 2 answer2_5
726 3 answer3_1
I want the users who has given answer of all questions and
we have predefined set of answers for each question.
like Question 1 can have answers from answer1_1, answer1_2, answer1_3
Question 2 can have answers from answer2_1, answer2_2, answer2_3
Initially, I tried query like this:
SELECT GROUP_CONCAT( DISTINCT CAST( User AS CHAR ) ) allUsers, COUNT( DISTINCT User ) totalUsers
FROM survey
WHERE
(
(
Question =1
AND Answer = 'answer1_2'
)
OR (
Question =1
AND Answer = 'answer1_2'
)
OR (
Question =1
AND Answer = 'answer1_3'
)
)
AND (
(
Question =2
AND Answer = 'answer2_1'
)
OR (
Question =2
AND Answer = 'answer2_2'
)
OR (
Question =2
AND Answer = 'answer2_3'
)
)
but then I see the result and realize that 'AND' among all questions won't work for my requirement
but I need the result with that logic.
Table structure cannot be changed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
You could do something like:
如果您在字段
User
和Question
上有唯一的键,那么您可以执行以下操作:您可以将 num_total_questions 作为应用程序中的变量传递
If you have a unique key on fields
User
andQuestion
, then you could do something like this:You could pass num_total_questions as a variable from application