[英]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_name和last_name列以填充full_name为NULL的 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_name
或last_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_name
或last_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? 只是想知道这是否是最佳方法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.