gpt4 book ai didi

mysql - 在连接表时,我们可以在连接条件中使用 Case When 创建列吗

转载 作者:行者123 更新时间:2023-11-29 16:11:57 25 4
gpt4 key购买 nike

如果我们在连接条件中创建列时使用案例...代码将运行。但这是正确的吗?如果是的话怎么执行?

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 同一级别的大多数查询中不可用。特别是,它们不可用于 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);

关于mysql - 在连接表时,我们可以在连接条件中使用 Case When 创建列吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com