简体   繁体   中英

WHERE claus after JOIN is slowing down my query

My Query:

SELECT source.name, file_info.*  
from FILE_INFO  
JOIN source  
ON source.id = file_info.source_ID  
where file_info.source_ID in 
     (select ID from Source where name like 'Donatello.%');  

My Tables:

FILE_INFO    
FILE_NAME | FILE_ID | SOURCE_ID | DATE_SEEN | CURRENT_STATUS  

SOURCE  
NAME | ID | CATEGORY   

Background:

In my database, files are associated with the sources who provided them. Each file is given a FILE_ID and each source has a ID (same as SOURCE_ID in table FILE_INFO). However, the table FILE_INFO doesn't hold the name associated with the SOURCE_ID.

I'm trying to print all lines where from the table FILE_INFO along with the respective SOURCE name furthermore, i only want lines where the source providing that file starts with "DONATELLO".

This query works for me, however it runs very slow. Is there a better approach on my code? It works fine until I add that last 'where' clause. When that's included, it runs quite slow.

I appreciate your input.

Would this not be the same?

SELECT source.name, file_info.*  
FROM FILE_INFO  
    JOIN source  
        ON source.id = file_info.source_ID  
WHERE source.name like 'Donatello.%'

You IN clause uses a sub query, and in queries the source table again.

Why not simply your SQL as follows?

SELECT source.name, file_info.*  
from FILE_INFO  
JOIN source  
ON source.id = file_info.source_ID  
where source.name like 'Donatello.%';  

Do you have an index on name column from source table?

Why don't you just write your query like that:

SELECT source.name, file_info.*  
from FILE_INFO  
JOIN source  
ON source.id = file_info.source_ID  
where source.name like 'Donatello.%';

What about the following ?

SELECT source.name, file_info.*  
from FILE_INFO  
JOIN source  
ON source.id = file_info.source_ID and source.name like 'Donatello.%';

Change the condition to a simple one and invert the table order:

SELECT source.name, file_info.*  
from source   
JOIN FILE_INFO
  ON source.id = file_info.source_ID  
where source.name like 'Donatello.%'

With indexes in source(name) and file_info(source_ID) .

This will be faster because the where clause can be spied to the first table in the join table list so indexes can be used with the condition.

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