sql - 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
我想知道是否可以idRef
从Table Example2
和Table Example3
这是我尝试过的,但我知道它错了
SELECT
Example2.Name AS NamePerson, Example3.Name AS NameAnimal
FROM
Example1 AS Exa
WHERE
Exa.idRef=Example2.idPerson
AND
Exa.idRef=Example3.idAnimal
解决方案
您可以使用两次存在:
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
存在于example2
or中的 s example3
。
或与left join
其他example1
2 个表一起使用:
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
推荐阅读
- c# - 当我尝试将文件复制到“//192.168.0.22”之类的共享路径时,访问被拒绝错误
- android - 如何获取回收站当前可见项目位置
- jquery - 如何格式化通过 AJAX 从 ASPX JSON 解析的日期?
- css - 有没有办法在反应中使用我的样式作为外部 css 文件?
- c - C中寄存器存储类的存储分配?
- cypress - 如何让赛普拉斯只处理可见元素?
- python - 如何解释 scipy.interpolate.splrep 的结果?
- r - 匹配R中的两个整数向量
- django-logging - Django 日志记录:django.db.backends 返回“(0.000) None; args=None”消息
- docker - .NET Core 2.2 docker core dumped 故障排除