MySQL:从两列中获取不同的值,并检查它们是否出现在同一个表的另外两列中

时间:2013-06-17 10:23:35

标签: mysql select join self-join

我现在已经用了很长一段时间来改变我的大脑。所以是时候问你们了。我有以下(简化的)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列)。

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:1)

这很容易,你只需要检查一个孩子是否已成为父母......并且因为每个家庭有两个孩子,你需要做两次(一次为孩子一次,另一次为孩子两次)你应该有所有成为父母的孩子的名单。在列表中列出它们之后,您只需要计算它们,看不需要复杂化容易的事情;)

  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)

    );

答案 1 :(得分: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

相关问题