我们可以使用Case在连接表时在连接条件中创建列时

问题描述 投票:0回答:2

如果我们在连接条件中创建列时使用case ...代码运行。但这是对的吗?如果这是如何执行的?

select *,
case when position('/' in pax_name)>0 
         then SUBSTR(pax_name, 1, position('/' in pax_name)- 1) 
          end as **lastname**, 
    CASE WHEN position('/' in pax_name)>0 
         THEN SUBSTR(pax_name, position('/' in pax_name) + 1, LENGTH(pax_name))  
         END as **firstname**
from o
inner join m
on o.record=m.record
and o.pax_first_name = **firstname**
and o.pax_last_name = **lastname**
mysql sql join condition case-when
2个回答
0
投票

select中定义的列别名在select的同一级别的大多数查询中都不可用。特别是,它们不适用于wherefrom条款。

你可以使用having完成这个:

select *,
       (case when position('/' in pax_name) > 0 
             then SUBSTR(pax_name, 1, position('/' in pax_name)- 1) 
        end) as lastname, 
       (case when position('/' in pax_name)  >0 
             then substr(pax_name, position('/' in pax_name) + 1, length(pax_name))  
        end) as firstname
from o inner join
     m
     on o.record = m.record
having o.pax_first_name = firstname and
       o.pax_last_name = lastname;

您可以简化逻辑。我想你只想要:

select *,
       (case when pax_name like '%'
             then substring_index(pax_name, '/', 1)
        end) as firstname,
       (case when pax_name like '%'
             then substring_index(pax_name, '/', -1)
        end) as lastname
from o inner join
     m
     on o.record = m.record
having o.pax_first_name = firstname and
       o.pax_last_name = lastname;

我还建议不要使用,所以:

select *,
       (case when pax_name like '%'
             then substring_index(pax_name, '/', 1)
        end) as firstname,
       (case when pax_name like '%'
             then substring_index(pax_name, '/', -1)
        end) as lastname
from o inner join
     m
     on o.record = m.record
        m.pax_name = concat_ws('/', o.pax_first_name, o.pax_last_name);

0
投票

使用子查询

select o1.* from (
select *,
case when position('/' in pax_name)>0 
         then SUBSTR(pax_name, 1, position('/' in pax_name)- 1) 
          end as **lastname**, 
    CASE WHEN position('/' in pax_name)>0 
         THEN SUBSTR(pax_name, position('/' in pax_name) + 1, LENGTH(pax_name))  
         END as firstname
from o
) o1 inner join m
on o1.record=m.record
and o1.pax_first_name = firstname
and o1.pax_last_name =lastname 
© www.soinside.com 2019 - 2024. All rights reserved.