简体   繁体   English

在where子句更好或join子句中使用条件?

[英]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. 但是此条件t.name = 'php'在第一个查询的JOIN子句中,而在第二个查询的WHERE子句中。 I want to know which one is better and why? 我想知道哪个更好,为什么?

Generally, adding condition in Where clause, makes the code more clearer. 通常,在Where子句中添加条件可使代码更清晰。 When you add them to the AND clause, it gives a feeling that JOIN is based on the combination of two fields. 将它们添加到AND子句时,会感觉到JOIN基于两个字段的组合。

Adding condition to Where clause, might help the optimizer to filter out the records even before joining, in case of large tables. 在大表的情况下,在Where子句中添加条件可能有助于优化器甚至在连接之前就过滤掉记录。 I would suggest to keep it in the WHERE clause. 我建议将其保留在WHERE子句中。

EDIT Also, refer to this related post: Join best practices 编辑另外,请参阅以下相关文章:结合最佳实践

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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