如果我们在连接条件中创建列时使用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**
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);
使用子查询
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