简体   繁体   中英

How to concatenate two strings in SQL statement?

The problem

I have a SQL database named "matches" with a textfield named "events". In this event there is some data and I want to add a string to this data. For example: the existing data is "Goal: Aguero" and I want to add, with a SQL statement, the data: ", Yellow card: Ozil", so that I get the result: "Goal: Aguero, Yellow: Ozil"

What I've already tried

I've tried many things but I don't get the right solution. I've tried the dot function: 'Goal' . 'Yellow' but it doesn't work. I've also tried the CONCAT() function, but it doesn't work too.

Some code that I've tried:

$sql = "UPDATE matches
SET events.UpdateBy = CONCAT('Goal: Aguero',' ','Yellow card: Ozil')
ORDER BY id DESC LIMIT 1";

$sql = "UPDATE matches
SET events = 'Goal: Aguero' . ' Yellow card: Ozil'
ORDER BY id DESC LIMIT 1";

Can anyone help me? Many thanks in advance!

You simply specify the column name as the first argument and use CONCAT_WS which is NULL safe ie it'll work even if events column is NULL:

UPDATE matches
SET events = CONCAT_WS(', ', events, 'Yellow card: Ozil')
WHERE ...

Demo on DB<>Fiddle

PS: I would rather suggest creating a table of events eg matchevents(id, event_id, event_type_id, player_id, time, etc) . It is better that way.

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