如何在SQL UPDATE CASES中使用多个条件?
COLUMN1 COLUMN2 COLUMN3
BG1 STANDARD
FOX1 STANDARD
BRB STANDARD
NBC STANDARD
FOX2 STANDARD
CNN3 STANDARD
GAM1 STANDARD
AI1 STANDARD
CQN3 STANDARD
GSM1 STANDARD
OFD1 STANDARD
REST NONSTANDARD
WEST NONSTANDARD
EAST NONSTANDARD
我想设置column3 = 1,其中COLUMN 1在以下任何一个名字中都会下降 (BG1,FOX1,BRB,NBC,CNN3,GAM1,AI1)和COLUMN2 =标准时
并设置column3 = -2,其中column1不是以下名称((BG1,FOX1,BRB,NBC,CNN3,GAM1,AI1)和Column2 = STANDARD。
我写了这些
UPDATE SET COLUMN3 = 1
WHERE (COLUMN2 = 'STANDARD' AND COLUMN1 = 'BG1' OR 'FOX1'OR 'BRB' OR 'NBC' OR 'CNN3' OR 'GAM1' OR 'AI1')
UPDATE SET COLUMN3 = -2
WHERE (COLUMN2 = 'STANDARD' AND COLUMN1 !='BG1' OR 'FOX1'OR 'BRB' OR 'NBC' OR 'CNN3' OR 'GAM1' OR 'AI1')
它不起作用。有什么建议吗?
答案 0 :(得分:0)
让我们先来看看这个:
UPDATE SET COLUMN3 = 1
WHERE (COLUMN2 = 'STANDARD' AND COLUMN1 = 'BG1' OR 'FOX1'OR 'BRB' OR 'NBC' OR 'CNN3' OR 'GAM1' OR 'AI1')
在WHERE子句的后半部分,您有OR 'FOX1'OR 'BRB' OR 'NBC' OR 'CNN3' OR 'GAM1' OR 'AI1'
此部分始终求值为False。您没有将这些文本与任何列进行比较。如果你将它们与没有brakcets的column1进行比较,它几乎总是会评估为true,因为有很多匹配,其中列具有其中一个值。
SELECT 1 and 0 and 0 or 1 or 0;
SELECT 1 and 'aa' or 'bbb'
第一个总是评估为真,第二个评估为假。这正是查询中发生的事情。重写为
UPDATE SET COLUMN3 = 1
WHERE (COLUMN2 = 'STANDARD' AND COLUMN1 = 'BG1') AND (column1 = 'FOX1' OR column1 = 'BRB' OR column1 = 'NBC' OR column1 = 'CNN3' OR column1 = 'GAM1' OR column1 = 'AI1')
可选地
UPDATE SET COLUMN3 = 1
WHERE (COLUMN2 = 'STANDARD' AND COLUMN1 = 'BG1') AND column1 = IN ('FOX1','BRB','NBC','CNN3','GAM1','AI1')
答案 1 :(得分:0)
您想使用in
:
UPDATE t
SET COLUMN3 = 1
WHERE COLUMN2 = 'STANDARD' AND COLUMN1 IN ('BG1', 'FOX1', 'BRB', 'NBC', 'CNN3', 'GAM1', 'AI1') ;
UPDATE t
SET COLUMN3 = -2
WHERE COLUMN2 = 'STANDARD' AND COLUMN1 NOT IN ('BG1', 'FOX1', 'BRB', 'NBC', 'CNN3', 'GAM1', 'AI1') ;
您还可以使用CASE
:
UPDATE t
SET COLUMN3 = (CASE WHEN COLUMN1 IN ('BG1', 'FOX1', 'BRB', 'NBC', 'CNN3', 'GAM1', 'AI1') THEN 1
ELSE -2
END)
WHERE COLUMN2 = 'STANDARD' ;
答案 2 :(得分:0)
UPDATE TableName SET COLUMN3 =' 1'
COLUMN2 =' STANDARD' AND column1 IN(' BG1',' FOX1',' BRB',' NBC',' CNN3',& #39; GAM1',' AI1')
UPDATE TableName SET COLUMN3 =' -3'
COLUMN2 =' STANDARD' AND column1 NOT IN(' BG1',' FOX1',' BRB',' NBC',' CNN3', ' GAM1',' AI1')