我有一个更新语句,用于更新字段x,y和z,其中id = xx。
在表格中,我有一些不同的x_created_datetime字段(对于不同人员维护/输入的记录的不同部分)。我想编写一个单独的查询,如果为null,将更新此字段,但如果不为null则不管它。
所以我拥有的是:
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp"
WHERE id = X
我需要的是一种添加以下内容的方法,但仍然总是更新以上内容:
scan_created_date = "current_unix_timestamp"
where scan_created_date is null
我希望我能在没有第二次交易的情况下做到这一点。关于如何实现这一目标的任何想法?
答案 0 :(得分:32)
这样做:
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp",
scan_created_date = COALESCE(scan_created_date, "current_unix_timestamp")
WHERE id = X
COALESCE
函数选择第一个非空值。在这种情况下,它会将日期戳scan_created_date更新为相同的值(如果存在),否则它将取代您"current_unix_timestamp"
替换的任何内容。
答案 1 :(得分:4)
我认为您正在寻找的是IF()
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp",
scan_created_date = IF(scan_created_date IS NOT NULL, "current_unix_timestamp", NULL)
WHERE id = X
答案 2 :(得分:3)
mySQL有一个IFNULL
函数,所以你可以这样做:
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp"
scan_created_date = IFNULL( scan_created_date, "current_unix_timestamp" )
WHERE id = X
答案 3 :(得分:2)
你可以使用COALESCE()返回第一个NON-NULL值:
scan_created_date = COALESCE(scan_created_date, "current_unix_timestamp")
答案 4 :(得分:1)
您可以这样做:
UPDATE newspapers a, newspapers b
SET a.scan_notes = "data",
a.scan_entered_by = "some_name",
a.scan_modified_date = "current_unix_timestamp",
b.scan_created_date = "current_unix_timestamp"
WHERE a.id = X AND b.id = X AND b.scan_created_date is not NULL
答案 5 :(得分:0)
它与Oracle的NVL相当。 您可以使用参数
在预准备语句中使用它,如下所示UPDATE
tbl_cccustomerinfo
SET
customerAddress = COALESCE(?,customerAddress),
customerName = COALESCE(?,customerName),
description = COALESCE(?,description)
WHERE
contactNumber=?