我知道我必须在这里遗漏一些简单的东西......但是我在编写SQL子查询时遇到了问题。鉴于以下数据
user_id question_id answer_text
89 1 value1
89 2 value2
80 2 value2
99 2 value2
96 1 value1
96 2 value2
111 1 value1
111 2 value2
我需要获取具有两个问题的user_id问题1 ='value1'并且有问题2 ='value2'
以上结果是使用此查询生成的:
SELECT `User_answer`.`user_id`, `User_answer`.`question_id`, `User_answer`.`answer_text` FROM `user_answers` AS `User_answer` WHERE `User_answer`.`question_id` IN (1, 2) AND `User_answer`.`answer_text` IN ('value1', 'value2')
但当然这会使回答问题1的用户返回“value1”但问题2的回答与“value2”完全不同(反之亦然)。
我需要能够添加更多条件,但我想我可以补充说,如果我至少可以使这两个工作。
答案 0 :(得分:0)
一种方法是使用自联接,例如
select a1.user_id, a1.answer_text AS Answer1, a2.answer_text AS Answer2
from user_answers a1 join user_answers a2 on a1.userid=a2.userid and a1.question_id=1 and a2.question_id=2
where a1.answer_text <> a2.answer_text
对不起,如果语法稍微偏离(我使用MySQL已经有一段时间了),但你明白了。
答案 1 :(得分:0)
我会使用这样的内连接来执行此操作:
SELECT
user_id
FROM
user_answers AS a1
INNER JOIN user_answers AS a2 ON
a2.user_id = a1.user_id
AND a2.question_id=2
AND a2.answer_text='value2'
WHERE
a1.question_id=1
AND a1.answer_text='value1'
转换为:
答案 2 :(得分:0)
我尝试在没有子查询的情况下这样做:
SELECT `User_answer`.`user_id`,
MAX(CASE `User_answer`.`question_id` WHEN 1 THEN `User_answer`.`answer_text` END) AS `q1_answer`,
MAX(CASE `User_answer`.`question_id` WHEN 2 THEN `User_answer`.`answer_text` END) AS `q2_answer`
FROM `user_answers` AS `User_answer`
WHERE (`User_answer`.`question_id` = 1 AND `User_answer`.`answer_text` = 'value1')
OR (`User_answer`.`question_id` = 2 AND `User_answer`.`answer_text` = 'value2')
GROUP BY `User_answer`.`user_id`
HAVING COUNT(DISTINCT `User_answer`.`question_id`) = 2;