INSERT INTO with SubQuery MySQL

前端 未结 5 1158
無奈伤痛
無奈伤痛 2020-12-02 19:39

I have this Statement:

INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
    VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE it         


        
5条回答
  •  星月不相逢
    2020-12-02 20:18

    I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.

    INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
    

    The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.

    For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.

提交回复
热议问题