WHERE的多个IN语句。这会返回好的数据吗?

时间:2010-05-11 19:09:46

标签: sql sql-server tsql

SELECT ['VISA CK  - 021810$'].[ACCT NBR     #1], ['VISA CK  - 021810$'].[ALT CUST NM  #1], ['VISA CK  - 021810$'].[LAST USED]
FROM ['VISA CK  - 021810$']
WHERE ['VISA CK  - 021810$'].[ALT CUST NM  #1] 
    IN (
        SELECT ['VISA CK  - 021810$'].[ALT CUST NM  #1]
        FROM ['VISA CK  - 021810$']
        GROUP BY ['VISA CK  - 021810$'].[ALT CUST NM  #1]
            HAVING COUNT(['VISA CK  - 021810$'].[ALT CUST NM  #1]) > 1
        )
    AND ['VISA CK  - 021810$'].[ACCT NBR     #1]
    IN (
        SELECT ['VISA CK  - 021810$'].[ACCT NBR     #1]
        FROM ['VISA CK  - 021810$']
        GROUP BY ['VISA CK  - 021810$'].[ACCT NBR     #1]
            HAVING COUNT(['VISA CK  - 021810$'].[ACCT NBR     #1]) > 1
        )

3 个答案:

答案 0 :(得分:0)

它是一个有效的SQL构造,但我们无法评论它是否有效。

您说的是:对于['VISA CK - 021810$']中的每一行,如果我在其相对的IN子句中找到[ACCT NBR #1][ALT CUST NM #1]的匹配项,则返回此行

答案 1 :(得分:0)

是的,它会返回好的数据。 WHERE子句将确保在使用AND时返回任何数据之前都会遵守两个IN子句。

答案 2 :(得分:0)

使用JOIN重写:

SELECT t.[ACCT NBR     #1], 
       t.[ALT CUST NM  #1], 
       t.[LAST USED]
  FROM ['VISA CK  - 021810$'] t
  JOIN (SELECT ['VISA CK  - 021810$'].[ALT CUST NM  #1]
          FROM ['VISA CK  - 021810$']
      GROUP BY ['VISA CK  - 021810$'].[ALT CUST NM  #1]
        HAVING COUNT(['VISA CK  - 021810$'].[ALT CUST NM  #1]) > 1) x ON x.[ALT CUST NM  #1] =   t.[ALT CUST NM  #1] 
  JOIN (SELECT ['VISA CK  - 021810$'].[ACCT NBR     #1]
          FROM ['VISA CK  - 021810$']
      GROUP BY ['VISA CK  - 021810$'].[ACCT NBR     #1]
        HAVING COUNT(['VISA CK  - 021810$'].[ACCT NBR     #1]) > 1) y ON y.[ACCT NBR     #1] = t.[ACCT NBR     #1]

确保它返回您期望的数据 - 之后调整。假设您提供的查询是正确的,JOIN通常比子查询更受欢迎,但查看和比较执行计划将告诉您哪种情况最适合您的情况。