如何找到所有的兄弟姐妹和同父异母的兄弟姐妹?

问题描述 投票:0回答:2

我需要找出Table_3是否包含了属于某个父母的孩子的所有兄弟姐妹。例如,我问孩子12(父母1=Charles)。Table_2告诉我他还有2个兄弟姐妹14和23。现在,我如何写一个SQL代码来找出Table_3是否包含所有的孩子,然后ONLY然后标志或做一些事情?

表_1

id | parent     
1  | Charles    
2  | Jack   

表2

P_Id | chld_Id 
 1   | 12    
 1   | 14 
 1   | 23
 2   | 7
 2   | 13

表3

chld_Id
 5 
 7 
 12 
 16 
 14 
 23 
 25

EDIT:格式化表格我忘了说,我用的是mySQL和PHP。

mysql sql inner-join
2个回答
0
投票

你可以得到孩子12的父母。

 select tt2.parent from table_2 tt2 where tt2.child_id = 12;

你可以得到这些父母的其他孩子。

select t2.*
from table_2 t2
where t2.parent in (select tt2.parent from table_2 tt2 where tt2.child_id = 12);

你可以检查他们是否失踪 table_3:

select t2.*
from table_2 t2
where t2.parent in (select tt2.parent from table_2 tt2 where tt2.child_id = 12) and
      not exists (select 1 from table_3 t3 where t2.child_id = t3.child_id);

0
投票

SQLFiddle示例

SELECT     table_2.chld_Id
         , SUM(
             CASE WHEN table_3.chld_Id IS NULL 
               THEN 1 
               ELSE 0
             END
           ) unfound_siblings

FROM      table_2 
JOIN      ( select p_Id from table_2 where chld_Id = 7 ) parent ON ( table_2.p_Id = parent.p_Id ) 
LEFT JOIN table_3  ON ( table_2.chld_Id = table_3.chld_Id ) 
GROUP BY  table_2.chld_Id
;

如果你想知道父母的ID,就像你在另一个评论中说的那样,只要把它添加到字段列表和 group by.

  • 取而代之的是 sum 句子 , count(table_3.chld_Id) found_siblings 反其道而行之
© www.soinside.com 2019 - 2024. All rights reserved.