将严格的业务逻辑谓词添加到 LEFT JOIN 条件

发布于 2024-11-08 14:01:41 字数 429 浏览 0 评论 0原文

这是理论/最佳实践征求意见。

我已经习惯于将 WHERE 子句和 JOIN 条件视为“托管”任何业务逻辑的好地方,这将使我的查询尽可能精确。

但我注意到添加不相关的业务逻辑作为 JOIN 条件可能违反“最佳实践”。例如:

         SELECT a.Id, b.Id
           FROM foo AS a 
LEFT OUTER JOIN bar AS b ON a.Id = b.Id 
                        AND GETDATE() >= "18/5/2011"

这个例子有点天真:在现实生活中,调用者确实需要附加条件,并且没有它实际上会产生不真实的结果(调用者必须在代码中进行过滤)。

请注意,对于 OUTER 连接,当逻辑要求时,不能将条件放在 WHERE 子句中。

This is theoretical/best practice request for opinions.

I have grown accustomed to viewing the WHERE clause and the JOIN conditions as a good place to "host" any business logic that will make my query as precise as possible.

But it was brought to my attention that adding unrelated business logic as a JOIN condition might be against "best practices". For example:

         SELECT a.Id, b.Id
           FROM foo AS a 
LEFT OUTER JOIN bar AS b ON a.Id = b.Id 
                        AND GETDATE() >= "18/5/2011"

The example is a little naive: in real life the additional condition is really required by the caller and not having it would actually produce untrue result (that the caller will have to filter in the code).

Note that with OUTER joins and when logic dictates it, placing the condition in the WHERE clause is not an option.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月苍老的讽刺 2024-11-15 14:01:41

出于这个原因,我一直习惯于将尽可能多的条件放入 JOIN 语句中,并且在许多地方(包括 Joe Celko 的著作)中读到,这是最佳实践所以。

JOIN 条件将会更快,因为它们排除了将行完全添加到组合表中的情况,其中在根据联接条件组合表后使用 WHERE 子句- 以及可能更大的数据集。在许多情况下,我确信优化器会智能地处理这个问题,并在可能的情况下应用 WHERE 条件,但这只是猜测,并且最多是特定于引擎的。

I have always made it a practice to put as many conditionals into the JOIN statements as possible for that reason, and have read in a number of places, including Joe Celko's writings, that it's a best practice to do so.

JOIN conditions are going to be faster as they exclude rows from being added to the combined table altogether, where a WHERE clause is used after the tables are combined based on the join conditions - and on, potentially, a much larger data set. In many cases, I'm sure the optimizer handles this intelligently and applies WHERE conditions where possible, but that's speculation, and would be engine specific at best.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文