简体   繁体   English

SQL(DB2)WHERE子句优化

[英]SQL(DB2) WHERE clause optimization

I gather a large list of products into an array that name a unique product by line and item. 我将大量产品收集到一个数组中,该数组按行和项命名唯一的产品。 Then I feed that to my SQL statement's WHERE clause. 然后,将其提供给SQL语句的WHERE子句。 When this list of products gets rather large my WHERE clause also expands to an ugly mess. 当产品列表变得很大时,我的WHERE子句也会扩展为一个丑陋的混乱局面。 So an example of what my WHERE clause can look like is below: 因此,以下是我的WHERE子句的示例:

 WHERE FOO = 'Y'
 AND ((iline = ? AND iitem = ? )
 OR (iline = ? AND iitem = ? ) 
 OR ... 
 OR (iline = ? AND iitem = ? ))

And so on, where each "iline = ? AND iitem = ?" 依此类推,每个“ iline =?AND iitem =?” are a unique product. 是独特的产品。 It's apparent I am no expert at this, but it seems like having the occasional 100+ ORs in my WHERE clause is not very efficient and I could be doing it better somehow. 显然,我不是专家,但是似乎在WHERE子句中偶尔有100个以上的OR并不是很有效,我可以通过某种方式做得更好。

Thanks. 谢谢。

You could use something like this: 您可以使用如下形式:

Presuming, iline has values like A,B,C,D,E.... and iitem posses 1,2,3,4,5... Now, you need combinations to be satisfied like 
(iline = 'A' AND iitem = '2'), 
(iline = 'E' AND iitem = '2'), 
(iline = 'B' AND iitem = '3'), 
(iline = 'A' AND iitem = '3'), 
(iline = 'E' AND iitem = '2'),
(iline = 'B' AND iitem = '4')

This can probably squeeze to 这可能会挤压到

WHERE FOO = 'Y'
AND (iline = 'A' and iitem IN ('2','3'))
AND (iline = 'B' and iitem IN ('3','4'))
AND (iline = 'E' and iitem IN ('2','3'))

Ideally, you'll need to add: 理想情况下,您需要添加:

  • An AND when you have a condition on iline 当您在iline上患有疾病时,AND
  • another literal to the IN of existing condition. 现有条件IN的另一个文字。 Say if you have to add a new condition (iline = 'B' and iitem = '5') , rather than adding a new OR, you could simply add a literal '5' to the existing iline = 'B' condition like (iline = 'B' and iitem IN ('3','4','5')) 假设您必须添加一个新条件(iline = 'B' and iitem = '5') ,而不是添加一个新的OR,您可以简单地在现有iline ='B'条件中添加一个文字'5',例如(iline = 'B' and iitem IN ('3','4','5'))

Hope I made my concept clear, please lemme know your questions. 希望我能阐明我的概念,请让我知道您的问题。

I doubt it is any more efficient, but you could use a case statement instead: 我怀疑它是否更有效率,但是您可以使用case语句代替:

WHERE 
  FOO = 'Y'
  AND iline = CASE iitem
                WHEN ? THEN ?
                WHEN ? THEN ?
                ...
              END

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

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