选择联接测试同一列上的两个不同数据集

时间:2017-11-09 23:58:17

标签: mysql sql join many-to-many

我有一个用户拥有并属于许多“活动”的数据库,这些活动按activity_type分组:

假设我有一个用户表

users
-------
id
name
.....

还有一个活动表和类型

activities
----------
id
name
activity_type_id

activity_types
--------------
id
name

和联接表

activities_users
------------------
user_id
activity_id

所以问题是:

如果我有activity_type ids 5和7,并且需要进行一个查询,该活动会带来参与类型为5和7的活动的用户。

如何实现此查询?

试过这个:

SELECT users.id, users.name, users.email, users.phone FROM users
JOIN activities_users ON (
  users.id = activities_users.user_id  AND
  (
    activities_users.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (5))
    AND
    activities_users.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (7))
  )
);

但是我知道我将有一个空集,因为第5行的activity_id永远不会在一个数据集中,而另一个数据集同时存在。

问候!

2 个答案:

答案 0 :(得分:0)

我认为我每次必须使用不同的名称对连接表进行两个不同的JOIN别名:

SELECT users.id, users.name, users.email, users.phone FROM users
JOIN activities_users AS au1 ON (
  users.id = au1.user_id  
  AND au1.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (5))
)
JOIN activities_users AS au2 ON (
  users.id = au2.user_id  
  AND au2.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (7))
)
group by users.id;

无论如何,仍然会欣赏更多最佳答案!

答案 1 :(得分:0)

SELECT *
  FROM users
 WHERE EXISTS
           (SELECT NULL
              FROM activity_types
                   INNER JOIN activities ON activities.activity_type_id = activity_types.id
                   INNER JOIN activities_users ON activities_users.activity_id = activities.id
             WHERE activity_types.id IN (5, 7)
               AND activity_users.user_id = users.id)