将表中的值插入另一个表中

时间:2017-03-12 17:08:54

标签: mysql sql select join insert-into

我尝试将let exercises = Array(userExercise.exercises) ms_price的值插入到另一个表中,该表是ms_nameservice_type列的记录。

ms_pricelist

service_amount

记录

| ms_priceID | ms_Name | ms_price |
|------------|---------|----------|
| 7894       |Casing   | 17.0897  |
| 7895       |Fan      | 69.9902  |

这是我的代码。

| customerID | service_type | service_amount |
|------------|--------------|----------------|
| 1000712    | Casing       |  17.2311       |
| 1000712    | Trunion      | 189.9900       |

它可以实现我的目的,但它添加了一个新的记录(编辑历史记录:列)。我想将其更新或插入到记录表中的现有记录中。

编辑

我只想更新一条将ms_name和ms_price(来自ms_pricelist表)的值插入service_type和service_amount(记录表)的现有记录。

因此,记录表最终将包含:

INSERT INTO records (service_type, service_amount)
    SELECT ms_pricelist.ms_name, ms_pricelist.ms_price
    FROM records JOIN
         ms_pricelist
    WHERE records.CustomerNumber='1' AND ms_pricelist.ms_priceID='1'

1 个答案:

答案 0 :(得分:1)

您需要id语句(如果您支持的数据库):

MERGE

如果你使用的数据库引擎没有CREATE TABLE ms_pricelist ( ms_priceID int, ms_Name nvarchar(50), ms_price money ) CREATE TABLE records ( customerID int, service_type nvarchar(50), service_amount money ) MERGE records USING ( SELECT 1000712 AS customerID, ms_name, ms_price FROM ms_pricelist wHERE ms_priceID = 7894 ) AS rows(CustomerID, Name, Price) ON records.service_type = rows.Name AND records.customerID = 1000712 WHEN MATCHED THEN UPDATE SET service_amount = rows.Price WHEN NOT MATCHED BY TARGET THEN INSERT(customerID, service_type, service_amount) VALUES (rows.CustomerID, rows.Name, rows.Price); ,那么你必须采用老式的方式;使用单独的MERGEINSERT

UPDATE

http://rextester.com/FEGQS79621