我有以下(简化的)表格:
structure_id | hash_id
1 1
1 2
1 3
2 4
2 5
2 1
3 6
3 1
3 4
我想得到重复哈希 id 的交集作为结果 - 这意味着本示例如下:
- 1 2 3
1 3 1 1
2 1 3 2
3 1 2 3
因为1和1结构ID共享3条记录,1和2共享1条记录,依此类推。SQL结果将是:
id | intersected_id | count
1 1 3
1 2 1
1 3 1
2 1 1
2 2 3
2 3 2
3 1 1
3 2 2
3 3 3
值得一提的是,该表约有 5 亿条记录,因此必须尽可能优化查询。我该怎么做?
到目前为止我尝试的是自加入:
SELECT t1.structure_id, COUNT(t1.hash_id) FROM table t1 INNER JOIN table t2 ON t1.structure_id != t2.strucutre_id AND t1.hash_id = t2.hash_id GROUP BY t1.structure_id;
但它无法正常工作 - 它会在所有其他结构 ID 中找到重复的行。
最佳答案
您可以通过自连接来完成此操作:
select t1.structure_id, t2.structure_id, count(*)
from test t1 join
test t2
on t1.hash_id = t2.hash_id
group by t1.structure_id, t2.structure_id;
关于mysql - 从表中获取自身的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619874/