首页 > 解决方案 > MySQL搜索一对多关系的重复项

问题描述

我需要在 MySQL 中找到最有效的方法来比较一对多关系的 2 个不同实例。拿这张桌子

CREATE TABLE `Table` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ParentID` int(11) NOT NULL,
  `ChildID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `pach` (`ParentID`,`ChildID`),
  KEY `ParentID` (`ParentID`),
  KEY `ChildID` (`ChildID`)
) ENGINE=InnoDB AUTO_INCREMENT=1;

insert into `Table` (`ID`,`ParentID`,`ChildID`) values
(1,1,1),
(2,1,2),
(3,1,3),
(4,1,4),
(5,2,1),
(6,2,3),
(7,3,1),
(8,3,3),
(9,3,4),
(10,4,1),
(11,4,4),
(12,4,3);

ParentID 3 具有与 ParentID 4 相同的一组子代,这就是我需要我的查询能够识别的内容 - 给定 ParentID=4,返回 ParentID 3,因为它具有完全相同的子代。

到目前为止,我唯一能想到的是一个非常丑陋的 group_concat 查询(见下文)。解决这个问题的更好方法是什么?

select distinct(b.ParentID)
from `Table` a, `Table` b where
(select group_concat(ChildID order by ParentID asc) from `Table` where ParentID=a.ParentID )
=
(select group_concat(ChildID order by ParentID asc) from `Table` where ParentID=b.ParentID )
and b.ParentID!=a.ParentID
and a.parentID=4;
+----------+
| ParentID |
+----------+
|        3 |
+----------+

标签: mysqlone-to-many

解决方案


推荐阅读