登录
首页 >  Golang >  Go问答

使用SQL左连接在3个表和空值之间建立关联

来源:stackoverflow

时间:2024-02-07 19:21:23 258浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《使用SQL左连接在3个表和空值之间建立关联》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我有以下表格:

  • 用户
id first_name last_name
1 olivia liam
2 oliver noah
  • 作业日志
id status supervisor_id
1 completed 1
2 supervisor approve 2
3 supervisor approve null
  • 作业提交
id status supervisor_id homework_log_id
1 approved 1 1
2 supervisor approve 2 2
3 supervisor approve 2 3

这是sql查询:

select
    hl.id as id
     , hl.status
     , concat(au.first_name, ' ', au.last_name) as supervisor_name
from homework_log as hl
         left join homework_submission as hs on hs.homework_log_id = hl.id
         left join user as u on u.id = hs.supervisor_id

当状态完成时,此查询将仅包含supervisor_name。我知道这是因为 left join (我们加入 homework_submission)而发生的。我想要的是当 homework_log 中的supervisor_id 具有值时还包括主管名称。

所以我将查询更新为:

select
     hl.id as id
     , hl.status
     , concat(au.first_name, ' ', au.last_name) as supervisor_name
     , concat(au2.first_name, ' ', au2.last_name) as supervisor_name2
from audit_logs as al
          left join homework_submission as hs on hs.homework_log_id = hl.id
         left join user as u on u.id = hl.supervisor_id
         left join user as u2 on u2.id = al.supervisor_id

注意:我将supervisor_name2和supervisor_name放在这里只是为了向您展示我的所有尝试。 当状态为“已完成”时:

  • supervisor_name2 有一个正确的值(打印所有行的主管名称)
  • supervisor_name 的值不正确(当 al.supervisor_id 为 null 时不打印主管名称)

当状态为“主管批准”时:

  • supervisor_name 具有正确的值,但supervisor_name 根本没有值。

我也发现了这个很好的解决方案:

select
     hl.id as id
     , hl.status
     , coalesce(concat(au.first_name, ' ', au.last_name), concat(au2.first_name, ' ',              au2.last_name)) as supervisor_name
from audit_logs as al
          left join homework_submission as hs on hs.homework_log_id = hl.id
         left join user as u on u.id = hl.supervisor_id
         left join user as u2 on u2.id = al.supervisor_id

结果是正确的,除非 homework_log 中的supervisor_id 为 null :(

我的问题是,当表 homework_log 和 homework_submission 中的supervisor_id 之一或两个都有值时,如何编辑此查询以包含主管名称。


正确答案


https://www.postgresql.org/docs/15/functions-string.html#id-1.5.8.10.7.2.2.5.1.1.1

正如您在文档中看到的,concat 忽略 null 参数,但保留并连接非 null 参数。因此 coalesce 无法按您的预期工作,因为在每个 concat 调用中,您至少有 1 个非 null 参数(即 ' ' 空白字符),因此每个 concat 调用将返回 ' 的全名'

如果您希望操作在任何操作数为 null 时返回 null,则可以使用 || 代替 concat。例如:

COALESCE(
    (u1.first_name || ' ' || u1.last_name),
    (u2.first_name || ' ' || u2.last_name)
)

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>