简体   繁体   中英

Concat string in mutliple rows with php/mysql or codeigniter

I would like to concat the same value to a field on multiple rows with a constraint..

With php/mysql, i'll do something like that:

$newdata = '33';

$sql = 'UPDATE users set relation=concat(relation,$newdata) 
       WHERE user_id IN (22, 31, 54)';

When the relation field is empty, this query is ok, but if the field is not empty (fe relation:'8,56,78') i would like to concat ',33' with the coma in addition.

Have you an idea of how to do this without using multiple queries? I'd like to know if there is a way to do this in codeigniter too.

Thank you !

try this query, if field will not have data than it will work in that case as well

$newdata = '33';

UPDATE users set relation = IFNULL (CONCAT( relation , $newdata ), $newdata) WHERE user_id IN (22, 31, 54)

SQL has IF-Statements:

"UPDATE users set relation= 
    CASE WHEN relation = '' 
        THEN $newdata 
        ELSE concat(relation,$newdata) 
    END
 WHERE user_id IN (22, 31, 54);"

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