仅当其他列中不存在值时才更新列

时间:2013-09-22 12:53:49

标签: mysql sql-update case

我有一个程序,向这两个参数发送2个字符串给PHP($ lic用于许可证,$ hwid用于hardwareid),我想更新列“hardwareid1,hardwareid2或hardwareid3”(其中值为每次登录都为NULL)但我不想用相同的值填充2列(例如hardwareid1和hardwareid2)!因此,如果来自$ hwid的值已经存在于这3列中的一列中,则不需要更新。

UPDATE  license
SET     hardwareID3 = CASE WHEN hardwareID1 IS NOT NULL AND
                                hardwareID2 IS NOT NULL AND
                                hardwareID3 IS NULL
                                THEN '$hwid' 
                                ELSE hardwareID3 END,
        hardwareID2 = CASE WHEN hardwareID1 IS NOT NULL AND 
                                hardwareID2 IS NULL 
                                THEN '$hwid' 
                                ELSE hardwareID2 END,
        hardwareID1 = CASE WHEN hardwareID1 IS NULL 
                                THEN '$hwid' 
                                ELSE hardwareID1 END
WHERE   code = '$lic'

解决方案:

 AND '$hwid' NOT IN (COALESCE(hardwareID1,hardwareID2,hardwareID3, 0))

2 个答案:

答案 0 :(得分:1)

即使设置了id3,您的代码也会更新hardwareId2和hardwareId1。不知道你想到达那里。

查看COALESCE() MySQL函数,以构建满足您需求的更复杂语句:)

答案 1 :(得分:-1)

向where子句添加条件:

update ...
set ...
where code = '$lic'
and '$hwid' not in (coalesce(hardwareID1,0), coalesce(hardwareID2,0), coalesce(hardwareID3,0))

请参阅SQLFiddle