簡體   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