我正在努力编写查询以获取仅与指定用户相关的线程。
我在下面包括了一些虚拟数据和表架构,以及一些边缘情况的预期输出。
感谢您的帮助。
+----+--------+
| id | name |
+----+--------+
| 1 | User 1 |
| 2 | User 2 |
| 3 | User 3 |
+----+--------+
+------+----------+
| id | title |
+------+----------+
| 1 | Thread 1 |
| 2 | Thread 2 |
| 3 | Thread 3 |
+------+----------+
+-----------+---------+
| thread_id | user_id |
+-----------+---------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
+-----------+---------+
伪查询
select all from threads where related user id's are exactly 1 and 2
预期产量
+------+----------+
| id | title |
+------+----------+
| 2 | Thread 2 |
+------+----------+
Thread 2
位于结果列表中,因为它仅与User 1
和User 2
相关。
Thread 1
不在结果列表中,因为它仅与User 1
相关,而与不 User 2
相关。>
Thread 3
不在结果列表中,因为它与User 1
和User 2
和 {{1} }。
答案 0 :(得分:1)
编辑以处理案例3
select t.id, t.title
from users u
inner join thread_user tu on tu.user_id = u.id
inner join threads t on t.id = tu.thread_id
inner join (select thread_id
from thread_user
group by thread_id
having count(*) = 2) sq on sq.thread_id = t.id
where u.id in (1,2)
group by t.id, t.title
having count(*) = 2
我不在我的开发环境中,因此无法检查语法的正确性,但是类似的事情应该起作用,
select t.id, t.title
from users u
inner join thread_user tu on tu.user_id = u.id
inner join threads t on t.id = tu.thread_id
where u.id in (1,2)
group by t.id, t.title
having count(*) = 2