开发者

why does this insert statement not work in mysql?

Here is my code snippets. I don't know why the insert statements (3rd snippet) do not work?

/* work nicely*/
    create table t1
    (
      a int,
      b varchar(255)
    );

/* work nicely*/
insert into t1 values (1,"one"),(2,"two");

/* Why does this one not work??? */
insert into t1 
values s开发者_运维百科elect * from t1;


In general, when you use the results of a SELECT query as the values for an INSERT query, you drop the VALUES keyword. This is true in MySQL as well:

INSERT INTO t1 
SELECT * FROM t1;

The version given above is fragile, though, since it relies heavily on the number, order, and type of columns in the source and target tables being the same (presumably in most real cases you won't be inserting values taken from the same table).

I recommend specifying columns explicitly when using INSERT..SELECT as a best practice:

INSERT INTO t1(col1, col2, col3)
SELECT colA, colB, colC FROM t2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜