简体   繁体   English

一张桌子上的MySQL动态交叉表数据透视表比较

[英]Mysql Dynamic crosstab Pivot comparison on one table

I have a many to many table setup. 我有很多表设置。 This is an example of table I am focusing on. 这是我关注的表的示例。

many_to_many_id, foreign_key_id many_to_many_id,foreign_key_id
1, 1 1、1
1, 2 一二
1, 3 一三
2, 1 2、1
2, 2 2 2
3, 1 3,1
3, 4 3 4

I need to given many_to_many_id 1 find any other many_to_many_ids that have matching foreign keys that exist within the first set. 我需要给many_to_many_id 1查找其他任何具有在第一组内存在的匹配外键的many_to_many_ids Given the first set 1, 2, 3 attached to many_to_many_id would return 2 as 1, and 2 are inside the set, but 3 would not be returned as 4 is not part of the test set. 给定第一个集合1、2、3附加到many_to_many_id将返回2,因为1和2在集合内,但不会返回3,因为4不是测试集合的一部分。 My boss has said I should use a dynamic cross tab to create two tables to compare with a join. 我的老板说过,我应该使用动态交叉表来创建两个表以与联接进行比较。 I have looked for examples but they have not been helpful. 我在寻找示例,但它们并没有帮助。

You can do this with a few simple sub-queries. 您可以通过一些简单的子查询来实现。 The first will make sure that for each many_to_many_id there is at least one foreign_key_id in the set you're looking for (1, 2, 3) and the second will make sure there isn't even one foreign_key_id not in the set you're looking for. 首先将确保每个many_to_many_id至少有一个foreign_key_id在设置你正在寻找(1,2,3),第二个将确保竟然没有一个foreign_key_id 不是在你的设置寻找。

SET @search_id = 1;

SELECT m.many_to_many_id FROM SampleTable m
WHERE m.many_to_many_id != @search_id
AND     EXISTS ( SELECT 1 FROM SampleTable a WHERE a.many_to_many_id = m.many_to_many_id AND a.foreign_key_id IN ( SELECT b.foreign_key_id FROM SampleTable b WHERE b.many_to_many_id = @search_id ) )
AND NOT EXISTS ( SELECT 1 FROM SampleTable a WHERE a.many_to_many_id = m.many_to_many_id AND a.foreign_key_id NOT IN ( SELECT b.foreign_key_id FROM SampleTable b WHERE b.many_to_many_id = @search_id ) )
GROUP BY m.many_to_many_id

SQL Fiddle Here SQL小提琴这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM