简体   繁体   中英

Using condition in where clause is better or join clause?

Please assume this queries:

SELECT p.* FROM posts p
JOIN posts_tags pt ON pt.post_id = p.id
JOIN tags t ON pt.tag_id = t.id AND t.name = 'php'

SELECT p.* FROM posts p
JOIN posts_tags pt ON pt.post_id = p.id
JOIN tags t ON pt.tag_id = t.id
WHERE t.name = 'php'

AS you know, both have an identical result. But this condition t.name = 'php' is in JOIN clause in the first query and it is on the WHERE clause on the second query. I want to know which one is better and why?

Generally, adding condition in Where clause, makes the code more clearer. When you add them to the AND clause, it gives a feeling that JOIN is based on the combination of two fields.

Adding condition to Where clause, might help the optimizer to filter out the records even before joining, in case of large tables. I would suggest to keep it in the WHERE clause.

EDIT Also, refer to this related post: Join best practices

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