sql - SQL 根据值是否存在为 case 设置值
问题描述
我正在根据用户在另一个表中的电子邮件从一个表中查找地址,然后获取结果列表并检查该地址是否具有存储在第三个表中的属性。该属性可能存在也可能不存在于第三个表中。如果是,我希望 sql 打印出“属性存在”,如果没有,则打印出“属性不存在”
属性通过地址 id 链接到地址,用户通过用户 id 链接到地址。
这是我到目前为止所拥有的:
select b.street, case
when c.entity_id = b.entity_id and c.attribute_id = 100 then 'Attribute Exists'
else 'Attribute Doesn't Exist'
end as isValue
from customer_entity as a, //Customer Details
customer_address_entity as b, //Address Details
customer_address_entity_int as c //Address Attribute
where a.email = 'customeremail@example.com'
and a.entity_id = b.parent_id
我在这个特定设置中遇到的问题在表 c 中。如果我包含它,我试图从中获取此信息的 3 个地址的循环次数与我存储在表 c 中的属性数量相同(在这种情况下,是表 c 中有 10 条记录的 10 倍,所以当我只想要 3) 时,我得到 30 个结果。
我无法过滤表 c 中的结果,因为可能匹配也可能不匹配,但我想以任何一种方式打印结果。对于选择案例,我还需要表 c。如果我摆脱了表 c,那么只有我想要结果的三个地址出现,但是我无法比较表 c 中的值。
简而言之,这就是我需要打印出来的:
street isValue
Street 1 Attribute Exists
Street 2 Attribute Exists
Street 3 Attribute Doesn't Exist
解决方案
我认为您的查询以这种方式编写会更容易理解:
select distinct
b.street,
case
when c.attribute_id = 100 then 'Attribute Exists'
else 'Attribute Doesn''t Exist'
end as isValue
from customer_entity as a //Customer Details
join customer_address_entity as b //Address Details
on a.entity_id = b.parent_id
left join customer_address_entity_int as c //Address Attribute
on c.entity_id = b.entity_id
where a.email = 'customeremail@example.com'
您可以b
加入c
. 如果c.attribute=100
是因为记录加入,那么如果不是这个字段将始终为NULL
. distinct
由于左连接,我包含了一个c
。
推荐阅读
- javascript - 如何在 React-Native 中创建 Intent 并将数据传递给它?
- django - 测试图像上传总是失败
- python - 将 DataFrame 与“不均匀”数据合并
- google-cloud-firestore - .json 文件中的 Cloud Firestore 敏感信息
- reactjs - 导出材质ui主题包
- reactjs - 用异步反应意外的令牌
- c# - C# WPF 应用程序中的 Keycloak:如何在普通 MVVM WPF 应用程序中访问 C# 中给定用户/密码的角色?
- javascript - 如何在考虑负值的情况下将 javascript BigInt 转换为 Uint8Array
- angular - Angular-cli 组件生成器在 Nativesctipt 中不起作用
- javascript - 如何在地图函数内部进行 api 调用,每次调用该 api 之间有延迟?