sql - 在 SELECT 语句中的 CASE 中重构 SELECT 的重复

标签 sql postgresql

如何重构此 select 语句以删除重复

select
    (
      case
      when (
        select my_product_int_attribute -- duplication
        from app_public.products
        where product_id = entry.product_id
      ) > 0 then 1
      when (
        select my_product_int_attribute -- duplication
        from app_public.products
        where product_id = entry.product_id
      ) = 0 then 0
      else null
      end
    )
from app_public.entries as entry
where entry.project_id = 1;

是否存在没有连接的简单选项,也许像 with 语句可以在 select 中使用?

注意

项目有多个条目,条目有一个产品

最佳答案

可以改用 CTE 吗?

;with products as (
select products.product_id, products.my_product_int_attribute 
    from app_public.products
    group by products.product_id, products.my_product_int_attribute 
)
select
(
  case
  when products.my_product_int_attribute > 0 then 1
  when products.my_product_int_attribute = 0 then 0
  else null
  end
)
from app_public.entries as entry
left join products on products.product_id = entry.product_id
where entry.project_id = 1;

关于sql - 在 SELECT 语句中的 CASE 中重构 SELECT 的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877577/

相关文章:

ruby-on-rails - 无法找到数据库条目,即使它存在

mysql - SQL(?)如何从面包屑中解析父类别以使用parentID更新字段?

sql - 从时间间隔数据绘制每小时条形图的优雅方法?

mysql - 在 Perl DBI 中处理大量结果的最有效方法是什么?

postgresql - 减少 postgresql 中的执行时间

postgresql 查找相似词组

sql - 如果满足条件则阻止插入

聚合函数的 SQL Server 性能问题

ruby-on-rails - mongo与postgres模型的关联

sql - 为什么 SQL "NOT IN"这么慢?