简体   繁体   English

MySQL更新/连接列(如果为NULL),则使用其他列中的数据

[英]MySQL update/concatenate column if NULL, using data from other columns

I have a contacts table: 我有一个联系人表:

id   first_name   last_name   full_name
1    John         Doe         -null-
2    -null-       -null-      Mike Willson
3    Dany         Jean        -null-
4    Peter        -null-      -null-

How can i merge first_name and last_name columns to fill full_name column where full_name is NULL ? 我如何合并first_namelast_name列以填充full_nameNULL的 full_name列?

I would like to get results as this: 我想要这样的结果:

id   first_name   last_name   full_name
1    John         Doe         John Doe 
2    -null-      -null-       Mike Willson
3    Dany         Jean        Dany Jean
4    Peter        -null-      Peter
UPDATE your_table
SET full_name = CONCAT_WS(' ', first_name, last_name)
WHERE full_name IS NULL
  AND COALESCE(first_name, last_name) IS NOT NULL

Will update the full_name if it's NULL and either first_name or last_name is not NULL. 如果full_name为NULL并且first_namelast_name不为NULL,则将更新full_name

Note that CONCAT_WS() will ignore NULL parameters. 请注意, CONCAT_WS()将忽略NULL参数。 So if first_name or last_name is NULL, you will only get the other value without the ' ' space. 因此,如果first_namelast_name为NULL,您将只获得另一个值,而没有' '空格。

See demo on db-fiddle.com 参见db-fiddle.com上的演示

I'm doing it this way - and it wors fine: 我正在这样做-很好:

UPDATE `conacts_table`
SET `full_name` = CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
WHERE `full_name` IS NULL

Just wonder if it's the optimal way to do it? 只是想知道这是否是最佳方法吗?

One option would be using CONCAT() , COALESCE() and TRIM() functions together : 一种选择是一起使用CONCAT()COALESCE()TRIM()函数:

UPDATE contacts_table
   SET full_name = TRIM(CONCAT( COALESCE(first_name,''), ' ', COALESCE(last_name,'') )) 

without a WHERE condition. 没有WHERE条件。

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM