【问题标题】:Select parent records with all children in MySQL在 MySQL 中选择所有子项的父记录
【发布时间】:2012-02-14 03:33:34
【问题描述】:

我有 3 张桌子:

  • 父母
  • 孩子
  • 父子

父子之间存在多对多关系,通过父子连接表实现。

我正在寻找一个查询,它将为我提供给定子 ID 列表的所有父母。 但是 - 它必须完全匹配,即只有当它完全设置了给定的子 ID 时,父级才必须匹配,即不少于,但也不少(我正在为“不多”的部分而苦恼)。

我有类似的要求:Select Parent Record With All Children in SQL 除了孩子可以有多个父母。

举个具体的例子:

select * from parent

parent_id  name
------------------------------------
1          Parent 1
2          Parent 2

select * from child

child_id  name
------------------------------------
1         Child 1
2         Child 2
3         Child 3

select * from parent_child

parent_child_id  parent_id  child_id
------------------------------------
1                1          1
2                1          2
3                1          3
4                2          1
5                2          3

即如果提供子 ID 1、2、3 必须返回父 ID 1,因为只有父 1 链接到所有 3 个给定的子 ID。

提供子 id 1 和 3,必须返回父 id 2,因为只有父 2 链接到 only 子 1 和 3

这是我在这里的第一个问题 - 希望没问题!

【问题讨论】:

  • 在提供的数据中,父 2 是否确实与 child_id 值 1 和 3 相关联?
  • 嗨,马克——你说得对。我修正了错误

标签: mysql sql


【解决方案1】:

试试:

select parent_id
from parent_child
group by parent_id
having count(child_id) = 2 and
       count(case when child_id in (1,3) then child_id end) = 2

- 用于 child_id 集 (1,3)。对于 child_id 集 (1,2,3),相应地更新 in 条件,并将 both = 2 条件更改为 = 3

【讨论】:

  • 这行得通...但是当我有大型数据集时,查询只是搅动...似乎聚合导致过多的颠簸。它用于“parent.id in (...) 语句。关于如何提高速度的任何想法?
  • 想通了。只需要从外部查询中添加另一个联接。奇迹般有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-01-11
  • 2016-01-27
  • 2021-12-30
  • 1970-01-01
  • 2017-07-15
  • 2020-09-15
  • 2016-09-08
  • 1970-01-01
相关资源
最近更新 更多