简体   繁体   中英

Is there something I can change to make my view run faster?

I just created a view but it is really slow, since my actual table has something around 800k rows.

Is there something I can change in the actual sql code to make it run faster?

Here is how it looks now:

Select B.*    
FROM    
    (Select A.*, (select count(B.KEY_ID)/77 
                  FROM book_new B 
                  where B.KEY_ID = A.KEY_ID) as COUNT_KEY

     FROM    
       (select *
        from book_new 
        where region = 'US' 
          and (actual_release_date is null or 
               actual_release_date >= To_Date( '01/07/16','dd/mm/yy'))
       ) A
   ) B

WHERE B.COUNT_KEY = 1 
   OR (B.COUNT_KEY > 1 AND B.NEW_OLD <> 'Old')

The most obvious things to do are add indexes:

  • Add an index on book_new(key_id)
  • Add an index on book_new(region, actual_release_date)

These are probably sufficient. It is possible that rewriting the query would help, but this is a good beginning. If you want to rewrite the query, it would help if you described the logic you are trying to implement.

There are many ways to solve this issue based on your needs

  • You can create an indexed view
  • You can create an index in the base tables which are used in this view.
  • You can use the required columns in the SELECT statement instead of using SELECT * FROM,
  • If the table contains many columns but you require only few columns, you can create a NON CLUSTERED INDEX with INCLUDE COLUMNS option which will reduce the LOGICAL READS.

For starters, replace the scalar subquery for COUNT_KEY with a windowed COUNT(*) .

SELECT * FROM 
(
select book_new.*, COUNT(*) OVER ( PARTITION BY book_new.key_id)/77 COUNT_KEY
        from book_new 
        where region = 'US' 
          and (actual_release_date is null or 
               actual_release_date >= To_Date( '01/07/16','dd/mm/yy'))
)
WHERE count_key = 1 OR ( count_key > 1 AND new_old <> 'Old' )

This way, you only go through the BOOK_NEW table one time.

BTW, I agree with other comments that this query makes little sense.

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