2014-01-23 81 views
1

我正在调整存储过程。存储过程正在执行SELECT,并且有大约50个WHERE条件。 SQL与以下类似。可否请您让我知道,如果有更好的方法来检查这些条件多个WHERE条件与不在

SELECT * FROM table A 
JOIN table B 
ON A.ID = B.ID 
WHERE 
    (
      (
      A.name = 'abc' 
      and B.AID not in (111, 222) 

      ) 
     or 

     (A.name = 'def' 
     and B.AID not in (222,1113,111,654,199,43,243,643,754244,2434) 
     ) 
     or 

     (
     A.name = 'etd' 
     and B.AID not in (111,345,54,34,454) 

     ) 
     or 

     (
     A.name = 'ent' 
     and B.AID not in (111,188,199,1647,128006) 
     ) 
     or 

     (
     A.name = 'yyy' 
     and B.AID not in (111,188,1113,1647) 
     ) 
     or 

     (
     A.name = 'uuu' 
     and B.AID not in (111,188,1113,1647) 
     ) 
     or 

     (
     A.name = 'jyf' 
     and B.AID not in (111,188,1647,344,45444,645) 
     ) 
     or 

     (
     A.name = 'tut' 
     and B.AID not in (111,222,1113,1647) 
     ) 

+0

嗯,当然看起来可怕。在不知道数据库模式是什么样子的情况下,很难告诉你如何改进。 –

+3

您可以将条件存储在表中,或多或少。然后加入这张桌子,而不是制定一个奇怪的一系列条件。这将更快,并为您提供记录系统的可能性。 (简单地加一句话,说这行“tut”,111是什么意思(以及为什么你不想拥有它)) – Ronald

+0

某些where子句有一些合并...... A.name ='uuu '和A.name ='yyy'具有排除的B.AID值的相同列表。否则,我认为有很多方法可以减少这种说法。 (如果有人有更好的答案,会很高兴地感到惊讶)。 – Twelfth

回答

1
  1. 创建一个表中的姓名和ID映射:

    Name AID 
    ------ ------ 
    abc  111 
    abc  222 
    def  222 
    def  1113 
    
    ..etc 
    
  2. 使用左连接排除匹配:

    SELECT * FROM table A 
    JOIN table B 
        ON A.ID = B.ID 
    LEFT JOIN Exclusions e 
        ON A.name = e.name 
        and B.AID = e.AID 
    WHERE e.name IS NULL -- not in exclusion table 
    

或NOT EXISTS:

SELECT * FROM table A 
    JOIN table B 
     ON A.ID = B.ID 
    WHERE NOT EXISTS(
     SELECT null FROM Exclusions e 
     WHERE A.name = e.name 
     and B.AID = e.AID 
     ) 
+0

非常感谢。左连接解决了我的问题。 – user3229801