MySQL insert with value from select

Viewed 47

I have this query:

INSERT INTO oc_stock_hpp (product_id, buy_price) 
VALUES (
'3337',
(SELECT buy_price
FROM oc_stock_hpp
WHERE product_id ='3337'
ORDER BY id DESC
LIMIT 1)
)

I get an error:

Table 'oc_stock_hpp' is specified twice, both as a target for 'INSERT' and as a separate source for data

What should I do?

1 Answers

You could use an insert-select statement and add the product_id to the query:

INSERT INTO oc_stock_hpp (product_id, buy_price) 
SELECT   product_id, buy_price
FROM     oc_stock_hpp 
WHERE    product_id = '3337'
ORDER BY id DESC LIMIT 1
Related