简体   繁体   中英

CONCAT or REPLACE based on existance of value in MySQL

I have a simple sql query like below

SELECT REPLACE('TEST ABC XYZ NO JJJG', 'DEF', 'YES')

This will return same string as old one. I want here 'TEST ABC XYZ NO JJJG YES' as out put. If text exists, it should replace the text, else it should be appended at the end of the string.

Assuming column contains 'TEST ABC XYZ NO JJJG', then you could write a query like this:

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

EDIT: To your comment (Simply change REPLACE() with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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