sql - 如何在没有联合条款的情况下进行优化?

标签 sql database tsql sql-server-2008-r2

是否可以在没有 union 子句的情况下编写以下查询。

select ProductId,ImageName,ImageType, ROW_NUMBER() over (order by ProductId desc) RowId 
from
                (
                    select p.id ProductId ,p.pic_image ImageName,'pic_image' ImageType
                    from product p
                    left outer join iimages_edited pe on p.id = pe.[id] 
                    where isnull(p.pic_image,'') <> '' and isnull(pe.pic_image,0)=0 
                    union
                    select p.id ProductId,p.pic_bimage ImageName,'pic_bimage' ImageType
                    from product p 
                    left outer join iimages_edited pe on p.id = pe.[id] 
                    where isnull(p.pic_bimage,'') <> '' and isnull(pe.pic_bimage,0)=0
                    union
                    select p.id ProductId,p.pic_limage ImageName,'pic_limage' ImageType
                    from product p 
                    left outer join iimages_edited pe on p.id = pe.[id] 
                    where isnull(p.pic_limage,'') <> '' and isnull(pe.pic_limage,0)=0 
                    union
                    select p.id ProductId,p.pic_blimage ImageName,'pic_blimage' ImageType
                    from product p 
                    left outer join iimages_edited pe on p.id = pe.[id] 
                    where isnull(p.pic_blimage,'') <> '' and isnull(pe.pic_blimage,0)=0 
                    union
                    select p.id ProductId,p.pic_cimage ImageName,'pic_cimage' ImageType
                    from product p 
                    left outer join iimages_edited pe on p.id = pe.[id] 
                    where isnull(p.pic_cimage,'') <> '' and isnull(pe.pic_cimage,0)=0       
            )t 

Above query has same table but different where condition, It is possible to do it in a single query ?

任何帮助将不胜感激!

提前致谢

最佳答案

您似乎每次都在使用不同的列重复相同的连接和过滤器。您可以使用 UNPIVOT 将它们转换为行,在每个表上,在连接之前:

select pe.ProductId, p.ProductId, p.ImageName, p.ImageType, ROW_NUMBER() 
over (order by p.ProductId desc) RowId 
from (
  select id as ProductId, ImageType, ImageName
  from product
  unpivot (
    ImageType for ImageName 
    in (pic_image, pic_bimage, pic_limage, pic_blimage, pic_cimage)
  ) t
) as p
left outer join (
  select id as ProductId, ImageType, ImageName
  from iimages_edited
  unpivot (
    ImageType for ImageName 
    in (pic_image, pic_bimage, pic_limage, pic_blimage, pic_cimage)
  ) t
) as pe
on p.ImageType = pe.ImageType
  and p.ProductId = pe.ProductId
where pe.ProductId is null

UNPIVOT 过滤 null 值,因此可能不需要 ISNULL

关于sql - 如何在没有联合条款的情况下进行优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800202/

相关文章:

sql - 如何在TSQL选择查询中将行转换为JSON?

sql - WHERE 子句中的日期范围从 90 天前到今天的日期

mysql - 连接表并选择外键,其中所有行都满足第一个表中的条件

mysql 重复插入和更新

mysql - 发现每个表的 MySQL 读/写

database - 大型数据库上的文本挖掘(数据挖掘)

sql - 有没有办法同时选择和更新行?

SQL 将一个表的聚合结果作为查询中的一列返回

Python,mysqldb错误1064

database - PowerBuilder数据库连接池?如何