从表1中的ID返回表2中的名称时出现问题

时间:2019-03-06 15:50:07

标签: sql-server

我在此查询中不断收到错误

我有两个表dbo.littersdbo.dogs

所有狗的信息都在dbo.dogs表中,并且仅由ID表中的dbo.litters引用。

版本2

Select 
    Puppy.Reg, Puppy.Name, puppy.LitterId, 
    p1.Reg, p1.Name, p2.Reg, p2.Name
From 
    dbo.Dogs Puppy 
Join 
    dbo.litters as p on Puppy.LitterId = p.Id
Join 
    dbo.Dogs as p1 on Puppy.Id = p.FatherId
Join 
    dbo.Dogs as p2 on Puppy.Id = p.MotherId
Where 
    puppy.Reg = 'xxxxx/xxxx' 

Results of the query version 2

我想显示小狗的母亲和父亲,并且此信息仅在dbo.litters表中。

我对此很陌生,看不到哪里出了问题。

Select 
    d.id, d.Reg, d.Name, d.LitterId, l.FatherId, l.MotherId
From 
    dbo.Dogs D 
inner join 
    dbo.Litters L on d.LitterId = l.Id
where 
    d.Reg = 'XXXXXX/XXXX'`

此查询返回我需要的信息,但不返回父母的姓名。

结果看起来像这样

ID      Reg nr       Name    LitterID     Father ID   MotherID
---------------------------------------------------------------
20590   xxxxx/xxxx   Fido    8525         11942       12007

我在小提琴中做了一个小版本,所以每个人都可以看到它的结构:)

Database in fiddle

Database in fiddle with solution

2 个答案:

答案 0 :(得分:0)

您使用别名作为表名,但在联接时未使用别名。这就是它引发错误的原因,因此在连接中使用别名:

Select 
    d.id, d.Regnr, d.Name, d.LitterId, l.FatherId, l.MotherId,D1.Name as fathername,
    D2.Name as motherName
From dbo.Litters L

left  join  dbo.Dogs D
     on d.LitterId = l.Id
    left join dbo.Dogs D1 on L.FatherId=D1.ID
    left join dbo.Dogs D2 on L.MotherId=D2.ID
where 
    d.Regnr = 'NO34567/2012'

id      Regnr      Name     LitterId    FatherId    MotherId    fathername  motherName
3   NO34567/2012    Fido     9000          2         1               king       Queen

答案 1 :(得分:0)

您需要有关垃圾的信息,因此这就是您的起点。接下来,您想限制一只幼崽的窝,所以您加入了这只狗,并过滤了它的reg。最后,您想添加有关其父母的信息,以便加入这些特定的狗。您最终会得到类似的东西:

Select puppy.Reg
,      puppy.Name
,      puppy.LitterId
,      dad.Reg
,      dad.Name
,      mom.Reg
,      mom.Name 
From   dbo.litters as l
Join   dbo.Dogs puppy
    on Puppy.LitterId = l.Id 
Join   dbo.Dogs as dad
    on dad.id = l.FatherId 
Join   dbo.Dogs as mom
   on  mom.Id = l.MotherId 
Where  puppy.Reg = 'xxxxx/xxxx'

我不得不猜测那些加入条件,因为您没有提供信息。