这里我有一个数据库表模式设计如下:
消息频道是用户参与对话的合理位置。现在给出一个uid列表(对于一对一的对话,它是一对,对于多参与者的对话,它是一个列表)我需要找出我们是否已经有一个对话的频道。
例如,使用以下样本数据集(56,62),它将返回cid = 6的现有通道。
mysql> select * from participant;
+-----+-----+
| cid | uid |
+-----+-----+
| 1 | 47 |
| 1 | 17 |
| 2 | 50 |
| 2 | 17 |
| 3 | 53 |
| 3 | 17 |
| 4 | 56 |
| 4 | 57 |
| 5 | 56 |
| 5 | 58 |
| 6 | 56 |
| 6 | 62 |
| 7 | 56 |
| 7 | 53 |
| 8 | 56 |
| 8 | 59 |
| 9 | 56 |
| 9 | 61 |
| 10 | 56 |
| 10 | 63 |
+-----+-----+
20 rows in set (0.01 sec)
mysql> select * from user;
+----+--------+
| id | name |
+----+--------+
| 17 | test17 |
| 47 | test47 |
| 50 | test50 |
| 53 | test53 |
| 56 | test56 |
| 57 | test57 |
| 58 | test58 |
| 59 | test59 |
| 61 | test61 |
| 62 | test62 |
| 63 | test63 |
+----+--------+
11 rows in set (0.00 sec)
mysql> select * from channel;
+----+-------+
| id | name |
+----+-------+
| 1 | ch1 |
| 2 | ch2 |
| 3 | ch3 |
| 4 | ch4 |
| 5 | ch5 |
| 6 | ch6 |
| 7 | ch7 |
| 8 | ch8 |
| 9 | ch9 |
| 10 | ch10 |
+----+-------+
10 rows in set (0.01 sec)
所以问题是,在SQL中查找现有频道的最有效方法是什么?
答案 0 :(得分:1)
一种方法使用聚合和having
:
select p.cid
from participant p
group by p.cid
having count(*) = <num users> and
sum(case when uid not in (<user list>) then 1 else 0 end) = 0;