[英]SELECTing rows where no other rows match
这开始似乎很简单,但它变得尴尬。
假设我们有一个包含...的表
+---------+-----------+
| chat_id | friend_id |
+---------+-----------+
| A | 1 |
| A | 2 |
| A | 3 |
| B | 1 |
| B | 2 |
| C | 1 |
| C | 2 |
| C | 3 |
| D | 1 |
| D | 2 |
| D | 3 |
| D | 4 |
| D | 5 |
| E | 0 |
| E | 1 |
| E | 2 |
| E | 3 |
| E | 4 |
| E | 5 |
| E | 6 |
| E | 7 |
| F | 0 |
| F | 1 |
| G | 1 |
| G | 2 |
+---------+-----------+
我希望只选择那些有friend_ids 1和2且没有其他friend_id的chat_id,SQL将返回什么样的B和G?
到目前为止,我提出的最好的是:
SELECT DISTINCT a.chat_id, COUNT(*)
FROM tt2 a
LEFT JOIN tt2 b
ON a.chat_id = b.chat_id
AND b.friend_id NOT IN (1,2)
WHERE a.friend_id in (1,2)
and b.chat_id IS NULL GROUP BY a.chat_id HAVING COUNT(*) = 2;
+---------+----------+
| chat_id | count(*) |
+---------+----------+
| B | 2 |
| G | 2 |
+---------+----------+
2 rows in set (0.00 sec)
为了防止我在寻找chat_id,只有1,2,3存在...
SELECT DISTINCT a.chat_id, COUNT(*)
FROM tt2 a
LEFT JOIN tt2 b
ON a.chat_id = b.chat_id
AND b.friend_id not in (1,2,3)
WHERE a.friend_id IN (1,2,3)
AND b.chat_id IS NULL
GROUP BY a.chat_id
HAVING COUNT (*) = 3;
+---------+----------+
| chat_id | count(*) |
+---------+----------+
| A | 3 |
| C | 3 |
+---------+----------+
但是这个表可能变得庞大,我需要快速的SQL,有没有人知道更好的方法?
为了尝试澄清......我得到了一堆friend_id,我希望得到chat_id,其中只有那些friend_id存在于chat_id ....而SQL很快(在sqlite上)
提前谢谢了!
这是一个应该能够限制所需数据量的选项
SELECT
d.chat_id,
COUNT(DISTINCT s.friend_id) AS matchedFriends,
COUNT(DISTINCT d.friend_id) AS totalFriends
FROM tt2 AS d
INNER JOIN tt2 AS s
ON s.chat_id = d.chat_id
AND s.friend_id IN (1,2)
GROUP BY d.chat_id
HAVING matchedFriends = 2
AND totalFriends = matchedFriends
内部联接s
确保它仅命中已经得到了所请求的朋友至少一个行。该matchedFriends计数检查很多的朋友要求如何被发现。
然后,总朋友数将检查该聊天中共有多少朋友。
最后,HAVING首先确保有2个匹配的朋友,然后检查朋友的总数等于匹配的朋友的数量。
这将要求您提供朋友列表和您正在寻找的一些朋友,但应该是有效的。
为了提高效率,请在(chat_id,friend_id)
上设置一个索引(如果你还没有,假设它在编写时是一个由两部分组成的PK)
尝试这个:
SELECT chat_id, GROUP_CONCAT(DISTINCT friend_id ORDER BY friend_id) AS friends
FROM table_1
GROUP BY chat_id
HAVING friends = '1,2'
注意:这适用于mysql但我怀疑它适用于sqlite。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.