[英]CONCAT or REPLACE based on existance of value in MySQL
我有一个简单的SQL查询,如下所示
SELECT REPLACE('TEST ABC XYZ NO JJJG', 'DEF', 'YES')
这将返回与旧字符串相同的字符串。 我想在这里说出“ TEST ABC XYZ NO JJJG YES”。 如果存在文本,则应替换文本,否则应将其附加在字符串的末尾。
假设column
包含“ TEST ABC XYZ NO JJJG”,那么您可以编写如下查询:
SELECT
IF(
REPLACE(column, 'DEF', 'YES') = column, -- If the replacement yielded no changes
CONCAT(column, ' ', 'YES'), -- Simply append the text
REPLACE(column, 'DEF', 'YES') -- Otherwise returned the replaced result
) AS replaced_column
编辑:对您的评论(只需用INSTR()
更改REPLACE()
INSTR()
):
SELECT
IF(
INSTR(column, 'DEF') = column, -- If the column contains the text
REPLACE(column, 'DEF', 'YES'), -- Replace the result
CONCAT(column, ' ', 'YES') -- Otherwise append the text
) AS replaced_column
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.