具有多个连接的sql中的case语句

时间:2015-09-23 21:22:09

标签: sql postgresql join

我有两张桌子连在一起并返回我想要的东西:

SELECT a, b, table_one.c, d, e
     , case table_three.c 
           when table_three.other_column_in_table_three ISNULL THEN true           
           ELSE false 
       END 
from table_one INNER JOIN....

我有第三个表table_three,它也有列c。我需要一个带有标志(如布尔值)的列,该列是否出现在第三个表中。 我一直试图为此做一个案例陈述和左连接,但我无法弄清楚语法。

我知道我可以把这个案例作为SELECT之后的另一列,比如:

create table #examplework (item varchar(1), start_Loc int, end_loc int, distance int)

insert into #examplework
select 'a', 5, 10, 5
union
select 'b', 14, 11, 3
union
select 'c', 20, 1, 19
union
select 'd', 10, 13, 3
union
select 'e', 10, 5, 5
union
select 'f', 10, 6, 4

create table #worktable (Workingpath varchar(900), Current_Step varchar(1))
declare @step varchar(1) = (select top 1 item from #examplework order by distance) 
declare @path varchar(900) = ''

while @step is not null
begin
insert into #worktable
select concat(@path, ',' , @step) as Workingpath, @step as CurrentStep

set @step = (select top 1 ew1.item 
             from #examplework ew
             join #examplework ew1 on ew.item != ew1.item
             where ew.item = @step
             and ew1.item not in (select Current_Step from #worktable)
             order by abs(ew.end_loc - ew1.start_Loc))
set @path = (select top 1 Workingpath from #worktable order by len(Workingpath) desc)

end

select top 1 * from #worktable
order by LEN(workingpath) desc

但我不确定这是否正确,我不知道如何在此查询中添加左连接。这是正确的想法,如果是的话,语法是如何工作的?

2 个答案:

答案 0 :(得分:2)

更简单的方法

select a, b, table_one.c, d, e
     , table_three.other_column is not null as flag
from table_one inner join table_two on table_one.d = table_two.c
     left join table_three on -- put here the relation rules between table_three
                              -- and the other tables

答案 1 :(得分:1)

在MSSQL中你可以尝试:

SELECT a, b, table_one.c, d, e, ISNULL(table_three.c, true)
from table_one
INNER JOIN table_two ON table_two.c = table_one.d
LEFT JOIN table_three ON table_two.c = table_three.c
相关问题