[英]How to copy a row in an SQL table, insert it into the same table, and append “-Copy” to the end of the name?
I need to copy a full row in an SQL table but add "-Copy" to the end of the MarketName for the copied row. 我需要在SQL表中复制完整的行,但在复制的行的MarketName的末尾添加“ -Copy”。 I have the following:
我有以下内容:
$CopyMarket = "INSERT INTO Markets (MarketName, Size)
(SELECT MarketName, Size)
FROM Markets
WHERE MarketID=$CopyID";
How do I append "-Copy" to the MarketName? 如何在MarketName后面附加“ -Copy”?
ie: The name is "Colorado," I want to copy it and insert as a new row as "Colorado-Copy" 即:名称是“ Colorado”,我要复制它并作为“ Colorado-Copy”作为新行插入
Thanks. 谢谢。
Use CONCAT function from MySQL to append or prepend data. 使用MySQL的CONCAT函数添加或添加数据。 Also work in standard SQL.
也可以在标准SQL中使用。
Append 附加
$CopyMarket = "INSERT INTO Markets (MarketName, Size)
(SELECT CONCAT(MarketName, '-Copy'), Size)
FROM Markets
WHERE MarketID=$CopyID"; // Field-Copy
Prepend 前置
$CopyMarket = "INSERT INTO Markets (MarketName, Size)
(SELECT CONCAT('Copy-', MarketName), Size)
FROM Markets
WHERE MarketID=$CopyID"; // Copy-Field
From MySQL documentation : 从MySQL文档 :
Returns the string that results from concatenating the arguments. 返回连接参数产生的字符串。 May have one or more arguments.
可能有一个或多个参数。 If all arguments are nonbinary strings, the result is a nonbinary string.
如果所有参数均为非二进制字符串,则结果为非二进制字符串。 If the arguments include any binary strings, the result is a binary string.
如果参数包含任何二进制字符串,则结果为二进制字符串。 A numeric argument is converted to its equivalent binary string form;
数字参数将转换为等效的二进制字符串形式; if you want to avoid that, you can use an explicit type cast, as in this example:
如果要避免这种情况,可以使用显式类型强制转换,如以下示例所示:
SELECT CONCAT(CAST(int_col AS CHAR), char_col);
CONCAT() returns NULL if any argument is NULL. 如果任何参数为NULL,则CONCAT()返回NULL。
mysql> SELECT CONCAT('My', 'S', 'QL');
-> 'MySQL'
mysql> SELECT CONCAT('My', NULL, 'QL');
-> NULL
mysql> SELECT CONCAT(14.3);
-> '14.3'
For quoted strings, concatenation can be performed by placing the strings next to each other: 对于带引号的字符串,可以通过将字符串彼此相邻放置来执行串联:
mysql> SELECT 'My' 'S' 'QL';
-> 'MySQL'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.