0

我有一个看起来像这样的个人资料:

profile_id | answer_id
----------------------
1                1
1                4
1               10

我有一个表格,其中包含民意调查受访者的回复列表,其结构如下:

user_id | answer_id
-------------------
1            1
1            9
2            1
2            4
2           10
3           14
3           29

如何选择在个人资料中给出所有答案的用户列表?在这种情况下,只有用户 2。

4

4 回答 4

5

您可以使用以下内容:

select user_id
from response r
where answer_id in (select distinct answer_id  -- get the list of distinct answer_id
                    from profile
                    where profile_id = 1)  -- add filter if needed
group by user_id  -- group by each user
having count(distinct answer_id) = (select count(distinct answer_id)  -- verify the user has the distinct count
                                    from profile
                                    where profile_id = 1)  -- add filter if needed

请参阅带有演示的 SQL Fiddle

或者另一种写法是:

select user_id
from response r
where answer_id in (1, 4, 10)
group by user_id
having count(distinct answer_id) = 3

请参阅带有演示的 SQL Fiddle

于 2013-01-28T22:43:48.607 回答
0

这是一个带有聚合的连接查询示例:

select a.user_id
from profile p full outer join
     answers a
     on p.answer_id = p.answer_id and
        p.profile_id = 1
group by a.user_id
having count(p.profileid) = count(*) and
       count(a.user_id) = count(*)

完全外连接将所有配置文件与所有答案匹配。如果两个集合完全匹配,则另一个集合的 id 中没有“null”。该having子句检查是否存在这种情况。

于 2013-01-28T22:45:06.823 回答
0
SELECT user_id 
FROM user_answer 
WHERE user_id in (SELECT user_id FROM profile WHERE answer_id = 1) AND
      user_id in (SELECT user_id FROM profile WHERE answer_id = 4) AND
      user_id in (SELECT user_id FROM profile WHERE answer_id = 10)
于 2013-01-28T22:46:28.687 回答
-1
SELECT *
FROM   table1
       INNER JOIN table2
         ON table1.answer_id = table2.answer_id
WHERE  table2.user_id = 2 

我想这可能是你要找的。

于 2013-01-28T22:43:24.253 回答