是否可以在一个查询中将字符串附加到多个匹配行

Is it possible to append string to many matching rows in one query

例如,我有以下 table:

Id Name Color
1 FirstCar White
2 SecondCar Yellow
3 ThirdCar Red
4 FourthCar White
5 FifthCar Green
6 SixthCar Blue

我需要实现的目标:将字符串“_123”附加到字段“Name”,用于“Name”为“SecondCar”、“FourthCar”或“SixthCar”的所有行,结果如下:

Id Name Color
1 FirstCar White
2 SecondCar_123 Yellow
3 ThirdCar Red
4 FourthCar_123 White
5 FifthCar Green
6 SixthCar_123 Blue

我该怎么做?

您可以使用 CONCAT,它将在我们匹配的 where name in ('SecondCar','FourthCar','SixthCar') 条件下应用 _123

UPDATE test set name = CONCAT(name,'_123') 
WHERE name IN ('SecondCar','FourthCar','SixthCar');

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fd790f9f30fecdb2f3dc22cb2d8ca0a5

注。这将更新现有数据

使用 CASE WHEN statement together with a CONCAT 函数非常简单:

SELECT
  id,
  CASE
    WHEN name IN ("SecondCar", "FourthCar", "SixthCar")
      THEN CONCAT(name, "_123")
    ELSE name
  END AS name,
  color
FROM your_table;