Using insert into … select results in a incorrect syntax near select, why?

后端 未结 6 1056
时光取名叫无心
时光取名叫无心 2021-02-05 02:46

How can I make a SELECT inside an INSERT operation?

insert into tableX (a_id, b_id) 
VALUES ((SELECT service_id 
         FROM tableY 
         WHERE id = 10, 2))         


        
6条回答
  •  生来不讨喜
    2021-02-05 03:05

    While my original answer gave a working solution, I was actually wrong about the cause of the error. There is nothing wrong with using a scalar subquery inside a VALUES clause. The problem with the statement in the question is simply that one parenthesis is in the wrong place; the scalar subquery must be enclosed in parentheses.

    This should work:

    insert into tableX (a_id, b_id) 
    VALUES (
      (SELECT service_id 
             FROM tableY 
             WHERE id = 10)
      , 2
      );
    

    Original Answer

    VALUES can only be used in conjunction with literal values. However, literal values can be used in a subquery. Do this:

    insert into tableX (a_id, b_id) SELECT service_id, 2 FROM tableY WHERE id = 10
    

提交回复
热议问题