我有 4 张桌子
users
| id |Username|
| 1 | John |
| 2 | Mike |
| 3 | Alex |
user_contacts
| user_id |contact_id|
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
contact_groups
| id | Group name |
| 1 | Group 1 |
| 2 | Group 2 |
| 3 | Group 3 |
user_contact_groups
| user_id |contact_group_id|
| 1 | 1 |
| 1 | 2 |
| 3 | 2 |
id 喜欢做的是拉出属于联系人组 1 和 3 的用户或用户 1 的联系人(在 table:user_contacts 中)。下面是代码,但它返回查询为空
SELECT DISTINCT a.* from users as a
WHERE EXISTS (SELECT * FROM user_contacts as b
WHERE b.user_id = 1) OR
(a.id IN (select c.user_id
FROM user_contact_groups as c
WHERE c.contact_group_id IN (1,3)));