使用SQL Query将值从一个表INSERT到另一个表

时间:2014-04-30 07:41:38

标签: mysql sql

我正在尝试运行此SQL查询:

INSERT INTO controldata (field,value) 
VALUES (customer_billing_product_type, 
  SELECT name from customer_billing_product_types)

customer_billing_product_types表中的所有行插入到controldata表中,字段始终为customer_billing_product_type,但我收到一条SQL错误:

#1064 - You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near 
'SELECT name from customer_billing_product_types)' at line 1 

2 个答案:

答案 0 :(得分:4)

您编写的INSERT期望插入一条记录,但随后在values中返回一整套记录。尝试将您的查询更改为

INSERT INTO controldata(field, value)
SELECT customer_billing_product_type, t.name FROM customer_billing_product_types t;

这将从t.name中选择所有customer_billing_product_types值,将customer_billing_product_type添加为列,并将所有结果插入controldata

答案 1 :(得分:0)

您使用的语法错误,请尝试以下操作:

INSERT into controldata (field1) SELECT name from customer_billing_product_types;

如果您想将字段保持为常量,则可以按以下方式使用:

INSERT into controldata (field,value) SELECT 'customer_billing_product_types',name from customer_billing_product_types;