案例 - 当一个订单 table 是一个列引用不同的选择退出
Case-When an order table were a column references different opt-put
我们有一个 Order
table。 Object_Id
列是组织 ID 或个人 ID 的键。 Order
table 中的 object_name
列标识 Object_id
是组织还是联系人。
我正在查询数据,以便在适用的情况下输出 Organisation.name
或联系人姓名 (concat(contact.forname, " ", contact.surname)
)。
我想我需要一个 Case
声明。下面是我一直在测试的SQL:
select
object_name,
object_id
case when Order.object_name = 'contact'
then Order.object_id = Contact.id
else Order.object_name ='organisation'
then Order.object_id = Organisation.name
end as object_test,
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id
您的代码存在一些语法问题。应该是这样的:
select
object_name,
object_id,
case when Order.object_name ='contact' then Contact.id
when Order.object_name ='organisation' then Organisation.name
else 'default_value' end as object_test,
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id
你快到了。当 Order.object_name ='contact'
时,您可以简单地使用 concat(contact.forname, " ", contact.surname)
。在 then
之后,您可以简单地指定 sql 引擎应该选择什么。
select
object_name,
object_id,
case
when Order.object_name = 'contact' then concat(contact.forname, " ", contact.surname)
when Order.object_name ='organisation' then Organisation.name
end as object_test
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id
我们有一个 Order
table。 Object_Id
列是组织 ID 或个人 ID 的键。 Order
table 中的 object_name
列标识 Object_id
是组织还是联系人。
我正在查询数据,以便在适用的情况下输出 Organisation.name
或联系人姓名 (concat(contact.forname, " ", contact.surname)
)。
我想我需要一个 Case
声明。下面是我一直在测试的SQL:
select
object_name,
object_id
case when Order.object_name = 'contact'
then Order.object_id = Contact.id
else Order.object_name ='organisation'
then Order.object_id = Organisation.name
end as object_test,
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id
您的代码存在一些语法问题。应该是这样的:
select
object_name,
object_id,
case when Order.object_name ='contact' then Contact.id
when Order.object_name ='organisation' then Organisation.name
else 'default_value' end as object_test,
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id
你快到了。当 Order.object_name ='contact'
时,您可以简单地使用 concat(contact.forname, " ", contact.surname)
。在 then
之后,您可以简单地指定 sql 引擎应该选择什么。
select
object_name,
object_id,
case
when Order.object_name = 'contact' then concat(contact.forname, " ", contact.surname)
when Order.object_name ='organisation' then Organisation.name
end as object_test
from Order
join Contact on Order.object_id = Contact.id
join Organisation on Order.object_id = Organisation.id