[英]Sql moving values from one column to two different columns
My problem is as follows - in the database I have a Products table with a size column.我的问题如下 - 在数据库中我有一个带有大小列的 Products 表。 However, I have now created two new columns x_size and y_size and I wanted to move the values from the size column to these 2 columns.
但是,我现在创建了两个新列 x_size 和 y_size,我想将值从大小列移动到这 2 列。 For example, in the database I have a record, where the size column value is 100x200, now I want to transfer '100' to the new x_size column and '200' to the y_size column, and so for each of the records in this table.
例如,在数据库中我有一条记录,其中大小列值为 100x200,现在我想将 '100' 传输到新的 x_size 列,将 '200' 传输到 y_size 列,因此对于此中的每条记录桌子。
I was trying with :我正在尝试:
UPDATE `post` SET `x_size `=`size`
UPDATE `post` SET `y_size `=`size`
But this updates the value of the entire size column, not just part of it.但这会更新整个 size 列的值,而不仅仅是其中的一部分。 I will be grateful for your help
我会很感激你的帮助
If you have multiple records that you want to transfer from size column, you could do fetch all the records from your table, and then split your size values using PHP explode() function.如果您有多个要从 size 列传输的记录,您可以从表中获取所有记录,然后使用PHP explode()函数拆分您的大小值。 Since you tagged Laravel, here's the simple Laravel solution:
由于您标记了 Laravel,这是简单的 Laravel 解决方案:
$products = Products::get();
foreach ($products as $product){
$size = explode('x', $product->size);
$product->x_size = $size[0]; //First element from exploded array
$product->y_size = $size[1]; //Second element from exploded array
$product->save();
}
Tinker output:修补匠输出:
>>> $size = '100x200';
=> "100x200"
>>> $exlpodedArray = explode('x', $size);
=> [
"100",
"200",
]
>>> $x_size = $exlpodedArray[0];
=> "100"
>>> $y_size = $exlpodedArray[1];
=> "200"
You can use substring_index()
:您可以使用
substring_index()
:
UPDATE post
SET x_size = substring_index(size, 'x', 1),
y_size = substring_index(size, 'x', -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.