sql - 如何连接三个表并将空白字段设置为空?
问题描述
我用full join
andleft join
来加入Person
,Tasks
和Task
表。屏幕上显示的结果导致行数大于六。未设置的字段具有价值NULL
,这很好。
使用这样可以获得预期的输出joins
,但是有必要使用允许连接公共字段的子句。我怎样才能做到这一点?
解决方案
ACROSS JOIN
产生你想要的所有组合。然后一个简单的外连接可以检索相关的行(如果它们存在的话)。
你没有提到你正在使用的数据库,所以一个失败的标准查询就可以了。例如(在 PostgreSQL 中):
select
row_number() over(order by p.id, t.id) as id,
p.name,
case when x.st is not null then t.hr end,
x.st
from person p
cross join tasks t
left join task x on x.personid_fk = p.id and x.taskid_fk = t.id
order by p.id, t.id;
结果:
id name case st
--- ----- ------ -----
1 Anna null null
2 Anna null null
3 Luo 13:00 true
4 Luo 14:00 false
5 John null null
6 John null null
请参阅DB Fiddle上的运行示例。
推荐阅读
- google-apps-script - Google Sheet 到 Firestore 多个文档
- sql - 分组个人的案例陈述返回错误答案
- python - Python 虚拟环境(venv)用户包
- java - LibGdx Box2dLights:如何让链灯向各个方向发光?
- python - 如何使用 Python 从出站 Twilio 调用中检索信息?
- python - 使用 Python Selenium 自动注册 LinkedIn,并且在定位电子邮件、密码以及同意和继续元素时遇到问题
- html - Rails Form_for 仅在 Chrome 浏览器中不提交参数
- android - JUnit 本地测试 - '未解决的参考:测试'
- python - 如何使用命令行并使用 pip 安装软件包?
- ruby-on-rails - 如何在不中断应用程序/迁移的情况下调整全球化翻译表