问题
I have table with this structure
ID | Parameter1 | Parameter 2 | Multiplication
1 | 1024 | 100 |
2 | 1200 | 200 |
3 | 1600 | 300 |
4 | 1900 | 400 |
I want to fill column Multiplication with combined string from Parameter 1 and Parameter 2
ID | Parameter1 | Parameter 2 | Multiplication
1 | 1024 | 100 | 1024_100
2 | 1200 | 200 | 1200_200
3 | 1600 | 300 | 1600_300
4 | 1900 | 400 | 1900_400
Help me please to create this SQLQuery
回答1:
Using SQL then the following query should work..
Assuming the Param fields are ints use cast to make them strings
UPDATE Table1 SET Multiplication = CAST(Parameter1 AS VARCHAR(10)) + '_' + CAST(Parameter2 AS VARCHAR(10))
Else if they are already strings (e.g., varchar, text) just don't cast. I.e.,
UPDATE Table1 SET Multiplication = Parameter1 + '_' + Parameter2
Just change Table1 to the name of your table
回答2:
An alternate for SQL Server is to add a column to handle this for you. It will automatically update the value if either parameter1 or parameter2 changes:
ALTER TABLE myTable
ADD myJoinedColumn AS CAST(Parameter1 AS VARCHAR(10)) + '_' + CAST(Parameter2 AS VARCHAR(10))
Or as @Scozzard mentions in his answer, if they are already strings:
ALTER TABLE myTable
ADD myJoinedColumn AS (Parameter1 + '_' + Parameter2)
回答3:
For MySQL:
update Table1 set
Multiplication = concat(cast(Parameter1 as char), '_', cast(Parameter2 as char))
More about cast and concat in MySQL 5.0 Reference Manual.
回答4:
update Table1 set Multiplication = CONCAT_WS('_',Parameter1,Parameter2)
回答5:
update tablename
set Multiplication = convert(varchar, Parameter1) + '_' + convert(varchar, Parameter2)
来源:https://stackoverflow.com/questions/9126202/sql-query-to-fill-column-with-combination-of-other-columns