当不为空时更新字段
我有一个更新语句,用于更新字段 x、y 和 z,其中 id = xx。
在表中,我有一些不同的 x_created_datetime 字段(针对由不同人员维护/输入的记录的不同部分)。我想编写一个查询,如果该字段为空,则更新该字段,但如果不为空,则保留它。
所以我所拥有的是:
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
我希望我可以在不向数据库进行第二个事务的情况下执行此操作。关于如何实现这一目标有什么想法吗?
I have an update statement that updates fields x, y and z where id = xx.
In the table I have a few different x_created_datetime fields (for different portions of the record that are maintained/entered by different folks). I'd like to write a single query that will update this field if is null, but leave it alone if is not null.
So what I have is:
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp"
WHERE id = X
What I need is a way to add in the following, but still always update the above:
scan_created_date = "current_unix_timestamp"
where scan_created_date is null
I'm hoping I can do this without a second transaction to the DB. Any ideas on how to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
执行此操作:
COALESCE
函数选择第一个非空值。在这种情况下,它会将日期戳 scan_created_date 更新为相同的值(如果存在),否则它将采用您替换"current_unix_timestamp"
的内容。Do this:
The
COALESCE
function picks the first non-null value. In this case, it will update the datestamp scan_created_date to be the same value if it exists, else it will take whatever you replace"current_unix_timestamp"
with.mySQL 有一个
IFNULL
函数,所以你可以这样做:mySQL has an
IFNULL
function, so you could do:我认为您正在寻找的是 IF ()
I think that what you're looking for is IF()
您可以使用 COALESCE() 返回第一个非空值):
You could use COALESCE() wich returns the first NON-NULL value):
你可以这样做:
You can do something like this:
它相当于 Oracle 的 NVL。
您可以像下面一样在使用参数的准备好的语句中使用它
Its like equivalent to Oracle's NVL.
You can use it like below in a prepared statement using parameters