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