我有一个名为 user_answers 的表。这是表的架构。
现在,我想创建一个可以适应不同条件的查询。
例如:
选择对问题 1405 回答 0 或对问题 1628 回答 3 的所有用户。
也可以像这样过滤
选择对问题 1405 回答 0 并且对问题 1628 回答 3 的所有用户。
我尝试在 stackoverflow 中搜索类似的查询,并发现了这个 sql query to select record having same id but different value in two columns 。我尝试实现它,但它无法适应 OR 条件,它只能满足 AND 条件。
我还尝试使用下面的查询,我认为该查询可能有效,但不会返回任何结果。
select * from user_answers
where
(user_id = user_id AND question_id= 1627 AND answer = 5)
AND (user_id = user_id AND question_id= 1626 AND answer = 0) ;
上面的查询有什么问题吗?或者有什么方法我可以尝试吗?
PS:不只限于一种条件。它可以是诸如以下条件的组合。 (Q1 : A1) AND (Q2 : A2) OR (Q3 : A3) 依此类推......
感谢您的回复。
最佳答案
这可以使用GROUP BY
来解决。
案例或
:
SELECT user_id
FROM user_answers
WHERE condition1 OR condition2
GROUP BY user_id
案例AND
:
SELECT user_id
FROM user_answers
WHERE condition1 OR condition2
GROUP BY user_id
HAVING count(*) = 2
关于mysql - SQL查询条件,用于根据条件获取用户的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41095597/