I have a DB with two columns with many records and from these two columns I have to do some mathematical operations and create other two columns.
For now I did like this:
Do you think there is a faster way to do it? I also tried like this:
UPDATE myTable SET X_GAUSS = (SELECT X FROM myTable ) + 1, Y_GAUSS = (SELECT Y FROM myTable) + 2
(it's only an example)
But in this way every line of the new columns is the same as the line before, instead I want something like:
X Y X_GAUSS Y_GAUSS
1 2 2 4
3 4 4 6
5 6 6 8
...
In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.
We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.
In MySQL, if you want to update a column with the value derived from some other column of the same table we can do so by using a SELF JOIN query and if you wish to modify the value derived from another column like maybe get a substring from the text or break the string using some delimiter, then we can use the ...
A subquery like SELECT X FROM myTable
returns the first row of the table.
You can simply access the columns of the same row directly:
UPDATE myTable
SET X_GAUSS = X + 1,
Y_GAUSS = Y + 2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With