Left join with condition

后端 未结 6 1015
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 21:17

Suppose I have these tables

create table bug (
    id int primary key, 
    name varchar(20)
)
create table blocking (
    pk int primary key,
    id int, 
          


        
相关标签:
6条回答
  • 2020-12-29 21:43

    It looks like you want to select only one row from #blocking and join that to #bug. I would do:

    select t1.id, t1.name, t2.name as `blockingName` 
    from `#bug` t1
    left join (select * from `#blocking` where name = "qa bug") t2
    on t1.id = t2.id
    
    0 讨论(0)
  • 2020-12-29 21:44
    select * 
    from #bug t1 
    left join #blocking t2 on t1.id = t2.id and t2.name = 'qa bug'
    
    0 讨论(0)
  • 2020-12-29 21:53

    make sure the inner query only returns one row. You may have to add a top 1 on it if it returns more than one.

    select 
    t1.id, t1.name,
    (select  b.name from #blocking b where b.id=t1.id and b.name='qa bug')
    from #bug t1 
    
    0 讨论(0)
  • 2020-12-29 21:59

    correct select is:

    create table bug (
    id int primary key, 
    name varchar(20)
    )
    insert into bug values (1, 'bad name')
    insert into bug values (2, 'bad condition')
    insert into bug values (3, 'about box')
    
    CREATE TABLE blocking
    (
    pk int IDENTITY(1,1)PRIMARY KEY ,
    id int, 
    name varchar(20)
    )
    insert into blocking values (1, 'qa bug')
    insert into blocking values (1, 'doc bug')
    insert into blocking values (2, 'doc bug')
    
    
    select 
    t1.id, t1.name,
    (select  b.name from blocking b where b.id=t1.id and b.name='qa bug')
    from bug t1 
    
    0 讨论(0)
  • 2020-12-29 22:03

    Simply put the "qa bug" criteria in the join:

    select t1.*, t2.name from #bug t1 
    left join #blocking t2 on t1.id = t2.id AND t2.name = 'qa bug'
    
    0 讨论(0)
  • 2020-12-29 22:07

    Here's a demo: http://sqlfiddle.com/#!2/414e6/1

    select
      bug.id,
      bug.name,
      blocking.name as blockingType
    from
      bug
        left outer join blocking on
          bug.id = blocking.id AND
          blocking.name = 'qa bug'
    order by
      bug.id
    

    By adding the "blocking.name" clause under the left outer join, rather than to the where, you indicate that it should also be consider "outer", or optional. When part of the where clause, it is considered required (which is why the null values were being filtered out).

    BTW - sqlfiddle.com is my site.

    0 讨论(0)
提交回复
热议问题