【问题标题】:Selecting two names based on ID stored in different table根据存储在不同表中的 ID 选择两个名称
【发布时间】:2020-11-26 00:37:40
【问题描述】:

假设我有两张桌子:

  • 表 1:具有列的任务(id、authorId、assigneeId)

  • 表 2:具有列(id、name)的员工

表1中的authorIdassigneeId引用了表2中的id列。

从这两个表中选择Task ID、Author Name和Assignee Name(如果没有assigneeId,Assignee name默认为'null')的方法是什么?

我不知道如何开始,因此很难。任何人都可以提示如何启动代码?

【问题讨论】:

    标签: sql left-join inner-join


    【解决方案1】:

    您可以加入两次:

    select t.id, e1.name as author_name, e2.name as assignee_name
    from tasks t
    left join employees e1 on e1.id = t.author_id
    left join employees e2 on e2.id = t.assignee_id
    

    【讨论】:

    • 谢谢。为了完成(如果 assigneeId 为空,则打印 null)从任务 t 中选择 t.id,e1.name 作为 author_name,IFNULL(e2.name,'null') 作为 assignee_name,在 e1.id = t 上加入员工 e1。 authorId 在 e2.id = t.assigneeId 上离开加入员工 e2;
    • 欢迎@user1453299。如果我的回答回答了您的问题,请点击复选标志accept it...谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2022-11-09
    • 2015-06-30
    相关资源
    最近更新 更多