0

我有这样的查询

SELECT *
FROM
table1,
table2,
table3,
table4,
table5,
table6,
table7,
table8
WHERE
a = b and
c = d and
e = d and
x1 = g and /*this is where x1 is changed into x2,x3,x4 or x5, labor intensive stuff*/ 
f = h and
i = j  

问题是某些 j 仅适用于某些 x1 到 x5 等等,它取决于名为 strfldvar 的字段中的变量。我所知道的是,只有当strfldvar = 'str1'x2 = g时,查询才适用于x1 = g strfldvar = 'str2'等等,所以我尝试了:

SELECT *
FROM
table1,
table2,
table3,
table4,
table5,
table6,
table7,
table8
WHERE
a = b and
c = d and
e = d and
(
(strfldvar = 'str1' AND x1 = g) 
OR (strfldvar = 'str2' AND x2 = g)
OR (strfldvar = 'str3' AND x3 = g)
OR (strfldvar = 'str4' AND x4 = g)
OR (strfldvar = 'str5' AND x5 = g)
)    and
f = h and
i = j 

这需要永远运行并在查询超时时停止。我猜想背后有一个笛卡尔积使得这变得如此复杂和耗时,所以查询显然有问题。我还尝试使用 CASE THEN 关闭所有在 WHERE 之后不相关的 '=' 并给出相同的结果。我可以通过实现 JOIN、LEFT JOIN、OUTER JOIN、INNER JOIN、UNION 或其他方式来更改我的查询,以使这项工作在所有 strfldvar 情况下都能快速工作,或者对此没有简单的答案?每种 strfldvar 类型的具体信息都连接到 table4 到 table8,str1 类型记录的附加信息保存在 table4 中,table8 和 str5 以及它们之间都相同。

我在这里做错了什么?

4

1 回答 1

1

您应该使用内连接而不是对整个表进行扫描。实际上,在您的情况下,您是从 8 表中选择数据,然后对整个数据进行扫描,这确实不是一个好技术。相反,您应该使用内连接,它将扫描您的序列基础结果并使您的查询相对较快。你的代码看起来像

SELECT * FROM table1 Inner join table2 On table1.a=table2.b
                    Inner join table3 On table2.b=table2.c    

等等..

于 2013-08-29T11:42:18.110 回答