开发者

SQL(DB2) WHERE clause optimization

开发者 https://www.devze.com 2023-03-25 00:40 出处:网络
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. When this list of products gets rather large my WHERE

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. When this list of products gets rather large my WHERE clause also expands to an ugly mess. So an example of what my WHERE clause can look like is below:

 WHERE FOO = 'Y'
 AND ((iline = ? AND iitem = ? )
 OR (iline = ? AND iitem = ? ) 
 OR ... 
 OR (ilin开发者_JAVA百科e = ? AND iitem = ? ))

And so on, where each "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.

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
  • another literal to the IN of existing condition. 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'))

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:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号