INSERT INTO with SubQuery MySQL

前端 未结 5 1164
無奈伤痛
無奈伤痛 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:29

    Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.

    INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
      SELECT
        /* Literal number values with column aliases */
        1 AS item_code,
        2 AS invoice_code,
        item_costprice
      FROM qa_items 
      WHERE item_code = 1;
    

    Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.

提交回复
热议问题