如何找到所有兄弟姐妹和半兄弟姐妹

时间:2014-11-28 13:37:05

标签: mysql sql mysqli inner-join

我需要找出Table_3是否包含属于某个父级的子级的所有兄弟姐妹。 例如,我询问孩子12(父母1 =查尔斯)。 Table_2告诉我他还有2个兄弟14和23.现在,我如何编写一个SQL代码来查明Table_3是否包含所有子节点,然后然后只是标记或对它做些什么?

表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

编辑:格式化表格 我忘了提到我使用mySQL和PHP

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

SQLFiddle Example

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执行相反的操作
相关问题