编写 SQL 子查询时出现问题
我知道我一定错过了一些简单的东西...但是我在编写 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
我需要获取同时具有 Question_id 1 = 'value1' 和 Question_id 2 = 'value2' 的 user_id
上面的结果是使用此查询生成的:
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')
但是当然,这会返回使用“value1”回答问题 1 的用户”但问题 2 的答案与“value2”完全不同(反之亦然)。
我需要能够添加更多条件,但我想如果我至少能让这两个条件正常工作,我可以添加这一点。
I know I must be missing something simple here...but I'm having problems with writing an SQL sub query. Given the following data
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
I need to get the user_id's that have BOTH question_id 1 = 'value1' AND have question_id 2 = 'value2'
The results above are generated using this query:
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')
but of course this returns users that have answered question 1 with "value1" but question 2 with a completely different answer than "value2" (and vice versa).
I need to be able to add in more conditions but I think I can add that if I can get at least these two working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法是使用自连接,例如,
抱歉,如果语法有点偏离(自从我使用 MySQL 以来已经有一段时间了),但你明白了。
One method is to use a self join, eg
sorry if the syntax is a little off (It's been a while since I used MySQL), but you get the idea.
我将使用如下内部联接来执行此操作:
翻译为:
I would do this using an inner join like this:
Translates to:
我会尝试在没有子查询的情况下执行此操作,如下所示:
I'd try doing it without a subquery, like this: