mysql - 在mysql db中获取集合的交集

标签 mysql sql intersection

我有下一个示例表:

+===========================+
| person_id | preference_id |
+===========+===============+
|     1     |       1       |
|     1     |       2       |
|     1     |       3       |
|     2     |       1       |
|     3     |       4       |
|     4     |       1       |
|     4     |       3       |
|     5     |       2       |
|     5     |       8       |
+___________+_______________+

我想获得 person_id 1 的前 10 个交集(是的,示例仅包含 5 个人)。 我是说: (1,2,3)∩(1)∩(4)∩(1,3)∩(2,8)

我们有四个集合的“person_id 1”的三个交集 对于 person_id 2:(1) 对于 person_id 4: (1,3) 对于 person_id 5: (2)

//person_id 3: no set that contains in person_id 1

而且……我们不知道 person_id 2、3、4、5 等。person_id 和 preference_id 包括超过 10000 行。 如你所见,我想要: - 在 mysql 中搜索交叉点的快速清洁方式 - 获得前 10 个交叉点(person_id 4 在职位数量的假设下最相关。然后是 2 和 5) 感谢您的关注。

最佳答案

SELECT t2.person_id, COUNT(*) int_size, GROUP_CONCAT(t2.preference_id) shared_preferences
FROM table t1
JOIN table t2 ON t1.preference_id = t2.preference_id
WHERE t1.person_id = 1
AND t2.person_id != 1
GROUP BY t2.person_id
ORDER BY int_size DESC
LIMIT 10

关于mysql - 在mysql db中获取集合的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19714830/

相关文章:

php - 在 php 中创建递归函数来重新构造记录集?

mysql - 使用最大数量按名称对 SQL 表进行排序

mysql - Ansible 没有安装最新版本的 Mysql 5.7

MySQL:WHERE 子选择中 GROUP BY 的奇怪行为

objective-c - 图形 - 我如何知道一条线是否在屏幕上可见(考虑到它的宽度)

mysql - 使用许多表创建 View ?

sql - 如何在 Excel 的 VBA 中使 ADODB.Connection 持久化?

mysql - 如何将 int 数字转换为时间 - SQL

objective-c - Cocoa NSRect 位于交叉点之外

C# 使用模式将两个字符串列表相交