开发者

INSERT statement with existing records

开发者 https://www.devze.com 2023-02-13 02:50 出处:网络
I was wondering if it is possible to do an insert statement with records that already exist. For example:

I was wondering if it is possible to do an insert statement with records that already exist. For example:

insert into tbl(item_name, item_price) values(select item_name, item_price from tbl where id = 5)

Say id is an auto incrementing pk.

When I try something similar to this, I'm getting errors:

Msg 156, Leve开发者_如何学Cl 15, State 1, Line 1
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.

Am I missing something, or is this just not possible?


Checkout this article: Adding Rows by Using INSERT and SELECT

Anyway the right way is the following:

insert into tbl(item_name, item_price) 
select item_name, item_price 
  from tbl 
 where id = 5


Try this:

insert into tbl(item_name, item_price) select item_name, item_price from tbl where id = 5


A subquery is possible in MySQL, but if you're doing it like this then your database is probably not normalized properly, and a design change would be your best move.

Here's the syntax for a subquery: http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号