首页 > 解决方案 > 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

标签: sqlmariadb

解决方案


我认为您的查询以这种方式编写会更容易理解:

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


推荐阅读