简体   繁体   中英

SQL Server - joining 4 fast queries gives me one slow query

I have 4 views in my MS Sql Server Database which are all quite fast (less than 2 seconds) and return all less than 50 rows.

BUT when I create a query where I join those 4 views (left outer joins) I get a query which takes almost one minute to finish.

I think the query optimizer is doing a bad job here, is there any way to speed this up. I am tempted to copy each of the 4 views into a table and join them together but this seems like too much of a workaround to me.

(Sidenote: I can't set any indexes on any tables because the views come from a different database and I am not allowed to change anything there, so this is not an option)

EDIT: I am sorry, but I don't think posting the sql queries will help. They are quite complex and use around 50 different tables. I cannot post an execution plan either because I don't have enought access rights to generate an execution plan on some of the databases.

I guess my best solution right now is to generate temporary tables to store the results of each query.

If you can't touch indexes, to speed up, you can put results of you 4 queries in 4 temp tables and then join them.

You can do this in a stored procedure.

You can have derived table of views while joining.

EXAMPLE: Instead of having this query

     SELECT V1.* FROM dbo.View1 AS V1 INNER JOIN dbo.View2 as V2
     ON V1.Column1=V2.Column1;

you can have the below query

     SELECT V1.* FROM (SELECT * FROM dbo.View1) AS V1 INNER JOIN (SELECT * FROM dbo.View2) AS V2
     ON V1.Column1=V2.Column1;

I hope this can impove the performance.

If you have many columns, only include the columns you need. Particularly, if you have many math operations on the columns, the database has to convert all of the numbers when it returns the results.

One more point is that it is sometimes better to do 3 queries than make a huge join and do 1 query.

Without specifics, however, it is difficult to give the right advice beyond generalities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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