Mysql 将表中的值插入到另一个表中
我试图将Mysql 将表中的值插入到另一个表中,mysql,sql,select,join,insert-into,Mysql,Sql,Select,Join,Insert Into,我试图将ms\u price和ms\u name的值插入另一个表中,该表是服务类型和服务金额列的记录 ms_价目表 | ms_priceID | ms_Name | ms_price | |------------|---------|----------| | 7894 |Casing | 17.0897 | | 7895 |Fan | 69.9902 | 记录 | customerID | service_type | service_amount
ms\u price
和ms\u name
的值插入另一个表中,该表是服务类型
和服务金额
列的记录
ms_价目表
| 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 |
这是我的密码
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'
它执行我想要的操作,但它添加了一条新记录(编辑历史记录:列)。我想更新或将其插入到我的记录表中的现有记录中
编辑我只想更新一条现有记录,该记录将把ms_name和ms_price的值(从ms_pricelist表)插入到service_type和service_amount(记录表)中 因此,记录表最终将包含:
| customerID | service_type | service_amount |
|------------|--------------|----------------|
| 1000712 | Casing | 17.0897 | <--Note: updated price
| 1000712 | Trunion | 189.9900 |
| 1000712 | Fan | 69.9902 | <--Note: new row
|客户ID |服务类型|服务金额||
|------------|--------------|----------------|
|1000712 | Casing | 17.0897 |您需要一个MERGE
语句(如果您拥有的数据库支持该语句):
如果你使用的数据库引擎没有MERGE
,那么你必须用老式的方法来实现它;使用单独的插入
和更新
:
--Add any missing rows
INSERT INTO records (customerID, service_type, service_amount)
SELECT 1000712 AS CustomerID, ms_name, ms_price
FROM ms_pricelist
WHERE ms_priceID = 7894
AND NOT EXISTS (
SELECT * FROM records
WHERE records.service_type = ms_pricelist.ms_name
AND records.customerID = 1000712)
--Update any existing rows
UPDATE records
SET service_amount = ms_pricelist.ms_price
FROM records
INNER JOIN ms_pricelist
ON records.service_type = ms_pricelist.ms_name
WHERE ms_pricelist.ms_priceID = 7894
AND records.customerID = 1000712
请用您正在使用的数据库标记您的问题。如果接受这种格式错误的语法,那么这可能就是MySQL。此外,样本数据和期望的结果将有助于解释您正在做什么INSERT
没有添加列,所以问题不清楚。我使用的是mysql。如果我使用UPDATE,它只会返回一堆错误,我就无法让它工作。也许用复制品什么的?我编辑了这个问题。是的,听起来像是重复密钥更新是你要找的。只需确保表中定义了主键#1064-您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,以了解第3行“从记录内部加入记录上的ms_价格表。服务_type=ms_pric”的正确语法。它在更新时返回此错误:(我是针对SQL Server编写的。您必须根据需要将其转换为mysql的SQL变体。
--Add any missing rows
INSERT INTO records (customerID, service_type, service_amount)
SELECT 1000712 AS CustomerID, ms_name, ms_price
FROM ms_pricelist
WHERE ms_priceID = 7894
AND NOT EXISTS (
SELECT * FROM records
WHERE records.service_type = ms_pricelist.ms_name
AND records.customerID = 1000712)
--Update any existing rows
UPDATE records
SET service_amount = ms_pricelist.ms_price
FROM records
INNER JOIN ms_pricelist
ON records.service_type = ms_pricelist.ms_name
WHERE ms_pricelist.ms_priceID = 7894
AND records.customerID = 1000712