我正在编写一个MYSQL查询来在向Oportunitati表添加新列之后更新数据库,但是嵌套的ifs不像我期望的那样工作。查询是:
UPDATE Oportunitati SET Stadiu =
if(Probabilitate < '20', '1',
if(Probabilitate < '40', '2',
if(Probabilitate < '60', '3',
if(Probabilitate < '80', '4',
if(Probabilitate < '100', '5',
if(Probabilitate = '100', '6', '7'))))))
如果Probabilitate介于0到20之间,我希望此查询将Stadiu设置为1,如果介于20和40之间,则设置为2,等等,如果是100则为7,如果超过则为
但是,即使我在所有括号中都有值,这个查询设置的唯一值是1和7.在mysql中我是否有任何关于嵌套IF的错误?
答案 0 :(得分:1)
case
而不是嵌套if
:
UPDATE Oportunitati SET Stadiu =
CASE
WHEN Probabilitate < 20
THEN 1
WHEN Probabilitate < 40
THEN 2
WHEN Probabilitate < 60
THEN 3
WHEN Probabilitate < 80
THEN 4
WHEN Probabilitate < 100
THEN 5
WHEN Probabilitate = 100
THEN 6
ELSE 7
END
答案 1 :(得分:0)
尝试此查询 -
UPDATE
Oportunitati
SET
Stadiu = IF(Probabilitate <= 100, Probabilitate DIV 20 + 1, 7);
如果您有负Probabilitate
,请再添加一个条件 -
IF(Probabilitate <= 100, IF(Probabilitate < 0, 0, Probabilitate) DIV 20 + 1, 7)