Select from same table as an Insert or Update

前端 未结 5 1745
走了就别回头了
走了就别回头了 2021-01-17 17:48

Clearly the following is incorrect.

INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),\'name\');

I get the value:

相关标签:
5条回答
  • 2021-01-17 18:28

    I take it that INSERT ... SELECT isn't working? I see this in the documentation for it:

    The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query. (This was not possible in some older versions of MySQL.) In this case, MySQL creates a temporary table to hold the rows from the SELECT and then inserts those rows into the target table.

    Out of curiosity, which version of MySQL are you using?

    0 讨论(0)
  • 2021-01-17 18:30

    as soon as the Select is correct you can do this.

    0 讨论(0)
  • 2021-01-17 18:33

    try:

    insert into aTable select max(a)^2, 'name' from aTable;
    

    or

    insert into aTable select max(a)^2, 'name' from aTable group by B;
    

    If you need a join, you can do this:

    insert into aTable select max(a)^2, 'name' from aTable, bTable;
    

    My "Server version" is "5.0.51b-community-nt MySQL Community Edition (GPL)"

    0 讨论(0)
  • 2021-01-17 18:33

    Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery.

    INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;
    

    A more complex example, where you have a corresponding secondary key and might be inserting the FIRST record for the corresponding secondary key:

    INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);
    

    By aliasing the table, it doesn't throw the error and seems to work. I just did this while coding something, although I can't see if there area any silly syntax errors above, I would try that type of syntax.

    0 讨论(0)
  • 2021-01-17 18:38

    I think you need to drop the "VALUES", and have a valid select statement.

    see this link

    I'm not particularly a mySQL guy, I use MSSQL mostly. But If you format the select statement correctly, It should work.

    0 讨论(0)
提交回复
热议问题