首页 > 解决方案 > 1 列引用,多表,可以吗?

问题描述

抱歉,标题不太清楚

这是我的桌子:

Table Example1

ID       idRef
-------------------
1         S1
2         D1

Table Example2  

ID       idPerson     Name
------------------------------
1        S1           Johnson   
2        S2           Scarlet
Table Example3
ID        idAnimal    Name
------------------------------      
1         D1          Lexa
2         D2          Jumanji

我想知道是否可以idRefTable Example2Table Example3

这是我尝试过的,但我知道它错了

SELECT 
    Example2.Name AS NamePerson, Example3.Name AS NameAnimal 
FROM 
    Example1 AS Exa 
WHERE 
    Exa.idRef=Example2.idPerson 
AND 
    Exa.idRef=Example3.idAnimal

标签: sqlsql-server

解决方案


您可以使用两次存在:

select idref from example1 e1
where 
  exists(
    select 1 from example2
    where idperson = e1.idref
  )
  or
  exists(
    select 1 from example3
    where idanimal = e1.idref
  )

这将返回idref存在于example2or中的 s example3
或与left join其他example12 个表一起使用:

select e1.idref 
from example1 e1 
left join example2 e2 on e2.idperson = e1.idref
left join example3 e3 on e3.idanimal = e1.idref
where e2.idperson is not null or e3.idanimal is not null

编辑。
要获取Name列:

select coalesce(e2.name, e3.name) name
from example1 e1 
left join example2 e2 on e2.idperson = e1.idref
left join example3 e3 on e3.idanimal = e1.idref
where e2.idperson is not null or e3.idanimal is not null

推荐阅读