mysql - 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 |
+----------+
解决方案
推荐阅读
- reactjs - 在 React 应用程序中使用 ActiveMQ
- laravel - Laravel 使用什么关系来查看来自另一个模型和列的数据
- c# - 在 ASP 控制器中创建数据库上下文实例是否有意义?
- raspberry-pi3 - 如何使用 Raspbian 在 Raspberry Pi 上设置联网的 Brother 打印机 (Brother_DCP_L2520DW_series)?
- android - 如何更改导航图标颜色
- azure-cosmosdb - 作为 cosmos db 中不支持的查询
- javascript - 在本机反应中运行 CPU 密集型任务
- excel - 一般问题:三人之间的平衡
- elasticsearch - 如何在 Elastic APM 中删除服务?
- python - 如何在您的分类机器学习模型中增加真阳性?