【问题标题】:MySQL: get distinct values from two columns and check whether they occur in two other columns of the same tableMySQL:从两列中获取不同的值并检查它们是否出现在同一张表的另外两列中
【发布时间】:2013-06-17 10:23:35
【问题描述】:

我已经为此绞尽脑汁很久了。所以是时候问问大家了。我有以下(简化的)MySQL 表,名为“fam”:

+--------------+------------+------------+-----------+-----------+
+ Year         + ParentID1  + ParentID2  + ChildID1  + ChildID2  +
+--------------+------------+------------+-----------+-----------+
+ 1970         + 1111       + 2222       + 3333      + 4444      +
+ 1975         + 1111       + 3434       + 4545      + 5656      +
+ 1980         + 2222       + 3344       + 5566      + 6677      +
+ 1990         + 5656       + 3333       + 9090      + 0909      +
+ 1995         + 4444       + 5656       + 1010      + 1313      +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

我基本上想要实现的是检查有多少孩子后来自己成为了父母。我认为这样的事情可能会起作用

SELECT COUNT(fam1.ChildID1)+COUNT(fam1.ChildID2) as `recruits`
FROM fam fam1
JOIN fam fam2
ON (fam1.ChildID1=fam2.ParentID1 OR fam1.ChildID1=fam2.ParentID2) 
OR (fam1.ChildID2=fam2.ParentID1 OR fam1.ChildID2=fam2.ParentID2) 

但是,可惜的是,新兵不是 8 人,而是只有 3 人(3333、4444 和 5656)。对我来说最大的问题是如何解释 ID 可以出现在不同列中的事实(例如 5656 在 1990 年的第 1 列和 1995 年的第 2 列)。

任何建议将不胜感激!

【问题讨论】:

    标签: mysql select join self-join


    【解决方案1】:

    检查一下

        select count(*) as `recruits` from
        (
         select  ChildID1 from fam
         where ChildID1 in 
         (select ParentID1 from fam 
           union 
          select ParentID2 from fam)
         union
    
         select ChildID2 from fam
         where ChildID2 in 
         (select ParentID1 from fam 
         union
         select ParentID2 from fam)
    
        )t;
    

    demo

    【讨论】:

    • 您的答案与我的基本相同,除了不同的论点。你不需要它,一个孩子只能属于一个家庭......因此使用distinct是没有意义的,只会使用计算机资源。
    • 这里的脸很结实。不知道为什么当解决方案实际上如此简单时,我一直在我的大脑中打结。干杯!
    【解决方案2】:

    这很简单,你只需要检查一个孩子是否已经成为父母......而且因为每个家庭都有两个孩子,你需要做两次(一个孩子一个,另一个孩子两个),你应该有所有成为父母的孩子的名单。将它们列入列表后,您只需计算它们,无需将简单的事情复杂化;)

      select count (*) from
        (
            select child1 from fam
             where child1 in 
                (select parent1 from fam 
                   union 
                  select parent2 from fam)
    
            union
    
            select child2 from fam
             where child2 in 
               (select parent1 from fam 
                 union
                select parent2 from fam)
    
        );
    

    【讨论】:

    • 非常感谢您的努力!非常感激!但是您的解决方案不是缺少所需的表别名吗?我接受了 echo_Samir 的解决方案,因为它是现成的,他不厌其烦地为它创造了一个小提琴。
    • @Tomm 他抄袭了我的答案...像他这样的人应该被禁止
    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2020-05-23
    相关资源
    最近更新 更多