新手需要多次选择同一个表

时间:2011-09-22 09:43:34

标签: sql sql-server tsql

我有一张包含人物信息的表格,例如

  • ID
  • Family(姓氏)
  • Name(名字)
  • Status
  • IDFather
  • IDMother

我想提出包含孩子的信息NameFamily,以及他们的父母的IDNameFamily,但只有那些父母死了的记录。到目前为止,我已经做到了这一点,但它只选择了已经死亡的孩子,而不是父母(状态5已经死亡)。

select * from A1 where (IDFather IS NOT NULL and IDMother IS NOT NULL) and [Status]   = '5'


Table sample below:
ID Family Name Status IDFather IDMother
001  Watson Jason  1    123      321
002  Smith  Matt   5    333      111
003  Smith  Mike   1    002      NULL
004  Derulo Sam    5    NULL     NULL
005  Pitt   Jenny  1    NULL     004

我试过这句话:

select * from Table1 where [Status] = '5'

然后我在C#

中写了一个select语句
select ID,Name,Family from Table1 where IDFather = "value" or IDMother = "value"

在一天结束时,我需要孩子的NameFamily以及父母的NameFamily父母ID。< / p>

2 个答案:

答案 0 :(得分:4)

select father.id,
        father.family, 
        father.name
        mother.id,
        mother.family, 
        mother.name
        child.id,
        child.family, 
        child.name
 from A1 father, 
      A1 mother, 
      A1 child
where child.IDFather = father.id
and   child.IDMother = child.id
and (father.status = 5 OR mother.status = 5)

如果要检索父母双方都已死亡的记录,请将OR替换为AND

哦,如果这是一个家庭作业,你可能想用更现代的白话改写我古老的连接语法。我陷入困境......

答案 1 :(得分:1)

试试这个:

SELECT * from your_table
WHERE 
    IDFather IN
    (SELECT ID from your_table WHERE Status = 5)
    AND IDMother IN
    (SELECT ID from your_table WHERE Status = 5)

如果你也想要死人,你可以试试:

SELECT * from your_table
WHERE 
    Status = 5
    OR (
    IDFather IN
    (SELECT ID from your_table WHERE Status = 5)
    AND IDMother IN
    (SELECT ID from your_table WHERE Status = 5))