繁体   English   中英

将where子句中的子查询移动到SQL Server中的表

[英]Move Subquery in the where clause to a table in SQL Server

我必须使用此查询来获得前1个订单:

select  top 1 ID
From    MyTable
Where   userid = @userid
and     ((type = 'SomeValue1' and status in (1,2) and convert(date,create_date) < convert(date,getdate())) OR
         (type = 'SomeValue2' and status in (1,3) and convert(date,create_date) < convert(date,getdate())) OR
         (type = 'SomeValue2' and status not in (1,3) and convert(date,create_date) = convert(date,getdate())))
and     active = 1
order by convert(date,create_date)

有没有办法,我可以将条件移到第一个“ AND”之后的where子句中,将“ type”,“ status”和“ Create_Date”与表进行比较,然后在where子句中使用它? 我要问的原因是,我必须做许多这样的比较,并且在一个查询中有30条不同的行会很笨拙。

另外,让我知道,如果我采用完全错误的方式。

提前致谢!

没有答案。 只有我的建议:

DECLARE @today date = cast(sysdatetime() AS date);

select top(1) ID
From    MyTable
Where   userid = @userid
and     ((type = 'SomeValue1' and status in (1,2) and cast(create_date AS date) < @today) OR
         (type = 'SomeValue2' and status in (1,3) and cast(create_date AS date) < @today) OR
         (type = 'SomeValue2' and status not in (1,3) and cast(create_date AS date) = @today))
and     active = 1
ORDER BY x
OPTION(RECOMPILE);
  • 然后在useridtypestatuscreate_date WHERE active = 1上添加过滤索引

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM