[英]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
要選擇 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.