[英]How to optimize the query? t-sql
This query works about 3 minutes and returns 7279 rows:此查询工作大约 3 分钟并返回 7279 行:
SELECT identity(int,1,1) as id, c.client_code, a.account_num,
c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
AND u.branch_id = @branch_id
ORDER BY c.client_code;
The type of 'client_code' field is VARCHAR(6). “client_code”字段的类型是 VARCHAR(6)。
Is it possible to somehow optimize this query?是否有可能以某种方式优化此查询?
Insert the records in the Temporary table without using Order by Clause and then Sort them using the c.client_code.在不使用 Order by Clause 的情况下将记录插入临时表中,然后使用 c.client_code 对它们进行排序。 Hope it should help you.希望它可以帮助你。
Create table #temp ( your columns... )创建表#temp(您的列...)
and Insert the records in this table Without Using the Order by Clause .并在不使用 Order by 子句的情况下插入此表中的记录。 Now run the select with Order by Clause现在使用Order by Clause运行 select
Do you have indexes set up for your tables?您是否为您的表设置了索引? An index on foreign key columns as well as Magazin.status might help.外键列上的索引以及 Magazin.status 可能会有所帮助。
Always try to list tables earlier if they are referenced in the where clause - it cuts off row combinations as early as possible.如果在 where 子句中引用了表,请始终尝试更早地列出表 - 它会尽早切断行组合。 In this case, the Magazin
table has some predicates in the where clause, but is listed way down in the tables list.在这种情况下, Magazin
表在 where 子句中有一些谓词,但在表列表中列在下方。 This means that all the other joins have to be made before the Magazin rows can be filtered - possibly millions of extra rows.这意味着必须在 Magazin 行被过滤之前进行所有其他连接 - 可能是数百万额外的行。
Try this (and let us know how it went):试试这个(让我们知道它是怎么回事):
SELECT ...
INTO #ttable
FROM accounts a
INNER JOIN Magazin m ON a.account_id = m.account_id
INNER JOIN Clients c ON c.id = a.client_id
INNER JOIN Uso u ON c.uso_id = u.uso_id
LEFT JOIN Users us ON m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9')
AND m.account_new_num is null
AND u.branch_id = @branch_id
ORDER BY c.client_code;
This kind of optimization can greatly improve query performance.这种优化可以大大提高查询性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.