use*_*439 0 sql sql-server performance select sql-like
如何改进下一个SQL Server查询?
SELECT SUM(Qty)
FROM Products
WHERE Type = 'SODA'
AND (Code LIKE 'A5%'
OR Code IN('DHA2','JHU8','KML2','LQA1','ZSX2'))
Run Code Online (Sandbox Code Playgroud)
执行需要大量时间.
提前致谢.
我通过Linked Server从DB2数据库获取数据.我不能只是阅读建立索引.
Id int
Name nvarchar(100)
Type nvarchar(100)
Code nvarchar(100)
Qty int
Run Code Online (Sandbox Code Playgroud)
首先,尝试创建索引products(type, code, qty).这可能会大大提高性能.
然后,如果这不起作用,请尝试将查询重写为:
select sum(qty)
from ((select qty
from products
where type = 'SODA' and
code like 'A5%'
) union all
(select qty
from products
where type = 'SODA' and
code IN ('DHA2','JHU8','KML2','LQA1','ZSX2'))
)
) t;
Run Code Online (Sandbox Code Playgroud)
这可能看起来更复杂,但有时会or干扰查询优化.