问题描述
||
这是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\'
)
)
但随后我看到了结果,并意识到所有问题中的“与”都无法满足我的要求
但我需要那种逻辑的结果。
表结构无法更改。
解决方法
您可以执行以下操作:
Select user,count(answer) from survey group by user having count(answer)=3
,如果您在字段User
和Question
上具有唯一键,则可以执行以下操作:
SELECT count(Question) answers_no,.... FROM survey GROUP BY User HAVING answers_no = num_total_questions
您可以将num_total_questions作为变量从应用程序传递