条件连接 - mysql 将如何智能地处理隐式信息

发布于 2024-10-16 03:12:18 字数 618 浏览 5 评论 0原文

刚刚遇到一个连接,只有在满足特定条件的情况下才需要连接。

所以我就想如果没有必要的话如何放弃join。

对 SO 的一些谷歌搜索和调查让我遇到了相当复杂的查询,涉及联合等。

让我向您展示两个表 t1 和 t2 的简单示例,其中有两个字段 id 和 val。

SELECT t1.id, t1.val, t2.val
FROM t1 
JOIN t2 ON t1.id = t2.id

现在 t1.val 可以有一个特殊值 -1,这使得连接变得多余,因为这样 t2.val 总是 NULL

SELECT t1.id, t1.val, IF(t1.val = -1, NULL, t2.val)
FROM t1 
JOIN t2 ON t1.id = t2.id

因此,如果我连接并且对连接表中字段的每个引用都是有条件的,并且不满足条件,那么连接肯定是多余的......MySQL是否认识到这一点并放弃连接?

因为我的数学直觉告诉我,这是一种标准情况,应该由像 MySQL 这样的专业数据库来有效处理。

有人有这方面的内幕消息吗?

最好的问候

拉斐尔

just came across a join which is only necessary given a certain condition is met.

So I thought about how to forego the join if it is not necessary.

Some googling and investigation on SO confronted me with rather complex queries, involving unions etc.

Let me show you a simple example for two tables t1 and t2 with two fields id and val.

SELECT t1.id, t1.val, t2.val
FROM t1 
JOIN t2 ON t1.id = t2.id

Now t1.val can have a special value -1, which makes joining superfluous, because then t2.val is always NULL.

SELECT t1.id, t1.val, IF(t1.val = -1, NULL, t2.val)
FROM t1 
JOIN t2 ON t1.id = t2.id

So, if I join and every reference to a field from the joined table is conditional and the condition isn't met, so the join is definitely superfluous ... does MySQL recognize that and foregoes the join?

Because my mathematical intuition tells me that this is a Std-situation that should be handled efficiently by a professional database like MySQL.

Has somebody insider information about that?

Best regards

Raffael

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

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

发布评论

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

评论(1

捎一片雪花 2024-10-23 03:12:18

连接条件(示例中为t1.id = t2.id)是确定结果行的唯一标准。由于连接条件中未引用 t1.val 的值,因此它不会影响包含或不包含的内容。如果您想在 t1.val 为 -1 时删除行,请在连接条件中包含一个测试:

SELECT t1.id, t1.val, t2.val
  FROM t1 
    JOIN t2 ON t1.id = t2.id AND t1.val != -1

如果您仍需要 t1 where t1.val=-1 中的行> 要出现在结果中,请使用 [LEFT JOIN]1,其中还包括 t1 中的所有行,其中 t2 中不存在具有相同 ID 的行:

SELECT t1.id, t1.val, t2.val
  FROM t1 
    LEFT JOIN t2 ON t1.id = t2.id AND t1.val != -1

The join condition (t1.id = t2.id, in the example) is the sole criteria for determining what the result rows are. Because the value of t1.val isn't referenced in the join condition, it won't affect what is or isn't included. If you want to elide rows whene t1.val is -1, include a test in the join condition:

SELECT t1.id, t1.val, t2.val
  FROM t1 
    JOIN t2 ON t1.id = t2.id AND t1.val != -1

If you still want the rows from t1 where t1.val=-1 to appear in the result, use a [LEFT JOIN]1, which will also include all rows from t1 where there is no row in t2 with the same ID:

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