繁体   English   中英

t-sql 2008 r2 where 语句有几个不是项目

[英]t-sql 2008 r2 where statement with several not items

在 t-sql 2008 r2 中,我试图确定如何设置 sql 以完成以下目标:

SELECT table1.customer_id, 
       type, 
       start_date, 
       end_date, 
       program_id 
FROM   table1 
       JOIN table2 
         ON table1.customer_id = table2.customer_id 
  1. where type not= ('aa','cc') and type not = 'g2' where code = 3 在 table1 中,每个 customer_id 都有很多记录,并且类型可以有很多不同的值。 我只想要不包含上面列出的值的 customer_ids。
  2. table2 只有一个 customer_id。 Customer_id 是table2 的key。 我希望客户在以下 3 列之一中没有值:start_date、end_date 和 program_id。

要选择 customer_id,上面列出的第 1 部分和第 2 部分都需要为真。 因此你能告诉我如何设置那个sql吗?

我不能确切地告诉你,因为我看不到你的数据库结构,但我相信它会是这样的:

   SELECT table1.customer_id,type,start_date,end_date,Program_id
    FROM table1 JOIN table2 ON table1.customer_id = table2.customer_id
    WHERE (table1.type NOT IN('aa', 'cc', 'g2') AND table1.code = 3)
    AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

将支票交给 Jason(+1) 但我会将条件加入到连接中
有时这有助于查询优化器

SELECT table1.customer_id,type,start_date,end_date,Program_id
  FROM table1 
  JOIN table2 
    ON table1.customer_id = table2.customer_id
   AND table1.type NOT IN ('aa', 'cc') 
   AND (table1.code = 3 and table1.type <> 'g2')
   AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

我明白这就是你真正要求的,但这不是你认为的

AND table1.type NOT IN ('aa', 'cc') 
AND (table1.code = 3 and table1.type <> 'g2')

是相同的

AND table1.type NOT IN ('aa', 'cc')
AND table1.type <> 'g2' 
AND table1.code = 3 

是相同的

AND table1.type NOT IN ('aa', 'cc', 'g2')
AND table1.code = 3

我想你的意思是要求是这样的

AND (    table1.type NOT IN ('aa', 'cc') 
      or (table1.code = 3 and table1.type <> 'g2') 
    )

尝试使用 INNER JOIN 怎么样:

SELECT table1.customer_id,type,start_date,end_date,Program_id
  FROM table1 
INNER JOIN table2 ON table1.customer_id = table2.customer_id
  WHERE table1.type != 'aa' 
    AND  table1.type != 'cc' 
    AND table1.type != 'g2'
    AND table1.code = 3
   AND (table2.start_data IS NULL OR table2.end_date IS NULL OR table2.program_id IS NULL)

让我知道它是否适合你!

Regrads, ANDOURA

暂无
暂无

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

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