如何获得仅与指定用户相关的第一个线程?

时间:2019-05-09 10:29:37

标签: mysql

我正在努力编写查询以获取仅与指定用户相关的线程。

我在下面包括了一些虚拟数据和表架构,以及一些边缘情况的预期输出。

感谢您的帮助。

用户

+----+--------+
| id | name   |
+----+--------+
|  1 | User 1 |
|  2 | User 2 |
|  3 | User 3 |
+----+--------+

线程

+------+----------+
| id   | title    |
+------+----------+
|    1 | Thread 1 |
|    2 | Thread 2 |
|    3 | Thread 3 |
+------+----------+

thread_user

+-----------+---------+
| 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 1User 2相关。

Thread 1 不在结果列表中,因为它仅与User 1相关,而与 User 2相关。

Thread 3 不在结果列表中,因为它与User 1User 2 {{1} }。

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