簡體   English   中英

MySQL:從兩列中獲取不同的值,並檢查它們是否出現在同一表的其他兩列中

[英]MySQL: get distinct values from two columns and check whether they occur in two other columns of the same table

我已經為此困擾了很長時間了。 所以是時候問你們了。 我有以下(簡化的)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) 

但是,las,只有8名新兵加入(3333、4444和5656)。 對於我來說,最大的問題是如何解釋ID可能出現在不同列中的事實(例如5656在1990年的第1列和1995年的第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)

    );

檢查這個

    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;

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM