【发布时间】:2014-12-04 17:15:08
【问题描述】:
我有几十个表,我必须使用三个字符串字段不断加入。
f1、f2 和 f3 始终不为空,并且它们每个都有固定数量的字符。
我知道这不是很优化,但我只能查询数据库,我不负责设计。
我用于查询的条件是:
concat(table1.f1, table1.f2, table1.f3) = concat (table2.f1, table2.f2, table2.f3)
这些查询针对的是拥有数百万个注册表的数据库,因此查询总是需要几分钟时间。
但是鞠躬,我想如果我写以下内容,也许连接会更快?
table1.f1 = table2.f1
and table1.f2 = table2.f2
and table1.f3 = table2.f3
我在想,也许这样数据库就可以利用索引来只连接所需的行?
有时我对必须连接的行非常严格,但我认为在连接查询中,所有行总是匹配的,一旦表被连接,这些行就会被丢弃。
如果我知道 table2.f6='whatever' 和 table2.f7='whatever' 等,那么查询连接所有行然后丢弃大部分行是否有意义?
因为我认为以下三个查询是相同的,就它们的优化程度而言。我说的对吗?
SELECT ...
FROM table1
INNER JOIN table2
ON table1.f1 = table2.f1
and table1.f2 = table2.f2
and table1.f3 = table2.f3
and table2.f6 = 'whatever here'
SELECT ...
FROM table1
INNER JOIN table2
ON table1.f1 = table2.f1
and table1.f2 = table2.f2
and table1.f3 = table2.f3
WHEN table2.f6 = 'whatever here'
SELECT ...
FROM table1, table2
WHEN table1.f1 = table2.f1
and table1.f2 = table2.f2
and table1.f3 = table2.f3
and table2.f6 = 'whatever here'
那么,我应该使用 concat 还是不使用,以及限制连接查询中的行以使其更快的最佳方法是什么?
谢谢!
【问题讨论】:
-
是的,这样的连接会阻止索引的使用,这意味着数据库必须从字段中创建新字符串,比较这些字符串,然后丢弃字符串。
-
你能不能给我一些参考,用一个不容置疑的参考来警告我的同事?
-
@user4126054 您要查找的词是sargable。
-
您使用 Teradata 标记了您的问题,但 CONCAT 在 Teradata 中不是有效的语法。关于这三种变体,它们都将返回相同的结果并且应该具有完全相同的计划(只要您不使用外连接)
-
毫无疑问,concat(string1, string2, ...) 在我的 Teradata SQL 助手中有效。