简体   繁体   中英

Writing conditions on Where clause is better or ON clause?

Which query is standard and optimal?

This:

SELECT p.*
FROM posts p
JOIN favorites f ON p.id = f.post_id
WHERE f.user_id = ? 

Or this:

SELECT p.*
FROM posts p
JOIN favorites f ON p.id = f.post_id
 AND f.user_id = ? 

Both query have written in standard way, it will work in almost all DBMS . But, if you concerned about the performance then i would use EXISTS instead.

select p.*
from posts p
where exists (select 1 
              from favorites f 
              where p.id = f.post_id and f.user_id = ?
             );

For me doing filter in ON clause or in WHERE clause just the metter of style how it looks for INNER JOIN . So, i would go with WHERE clause :

SELECT p.*
FROM posts p INNER JOIN 
     favorites f 
     ON p.id = f.post_id
WHERE f.user_id = ? 
ORDER BY f.date_time DESC;

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