【问题标题】:Can we use Case When created column in join condition while joining tables我们可以在连接表时在连接条件中使用 Case When created 列吗
【发布时间】:2019-08-06 09:41:49
【问题描述】:

如果我们在连接条件中创建列时使用 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 特别是为此使用 HAVING 子句。

标签: mysql sql join conditional-statements case-when


【解决方案1】:

select 中定义的列别名在select 的同一级别的大多数查询中不可用。特别是,它们不适用于 where 或 from 子句。

您可以使用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);

【讨论】:

    【解决方案2】:

    使用子查询

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2021-11-24
      • 2015-04-08
      相关资源
      最近更新 更多