查询以从每个问题的答案集中选择已回答所有问题的用户

时间:2011-05-24 07:24:34

标签: mysql

这是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'对我的要求不起作用 但我需要那个逻辑的结果。

表结构无法更改。

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

Select user, count(answer) from survey group by user having count(answer)=3

答案 1 :(得分:0)

如果您在字段UserQuestion上有唯一键,那么您可以执行以下操作:

SELECT count(Question) answers_no, .... FROM survey GROUP BY User HAVING answers_no = num_total_questions

您可以将num_total_questions作为变量从应用程序

传递