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

后端 未结 6 1055
时光取名叫无心
时光取名叫无心 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 02:48

    you don't need the values word.

    here is some documentation for mysql

    http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

    also, when you specify the columns into which the values should be inserted, you need to make sure your select returns the same number/types appropriate to what you specified.

    0 讨论(0)
  • 2021-02-05 02:49

    Try:

    insert into tableX (a_id, b_id)
    SELECT service_id, 4 as QUESTIONMARK FROM tableY WHERE id in (10, 2);
    

    This works on many database engines however we don't know what environment you are working on.

    EDIT: What is the second insert supposed to be?

    0 讨论(0)
  • 2021-02-05 03:01

    You're telling the DBMS that you're inserting two values (a_id, b_id) but only selecting one (service_id).

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-05 03:08

    You don't need the values key word and also you can add the default value 2 for b_id column in the select list instead of adding it after the SELECT statement

    Try this:

    INSERT INTO tableX (a_id, b_id) 
    SELECT service_id, 2 
      FROM tableY 
     WHERE id = 10
    
    0 讨论(0)
  • 2021-02-05 03:10

    In MySQL one can insert dynamic values. Here is the sample:

    INSERT INTO Item_Info (`Back_Ground_Color`,) 
    VALUES ( (select concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0)),-6))));
    
    0 讨论(0)
提交回复
热议问题