Tuesday, 13 August 2013

Insert new row with values relating to existing rows

Insert new row with values relating to existing rows

I am trying to insert a new row where one of the columns is a function of
the MAX of that column from the values that are already there. I know I
can do this easily with PHP by setting a temporary variable and doing two
queries, but I was just wondering if you can do this in pure MySQL.
First I tried this (note, the query contains much more, but this is what
was messing up):
INSERT INTO tbl
(column_name)
VALUES (
max( column_name ) + 6
)
Which produces the following error:
1111 Invalid use of group function
Then I tried:
INSERT INTO tbl
(column_name)
VALUES (
( SELECT max( column_name ) + 6 FROM tbl )
)
Which produces the following error:
1093 You can't specify target table 'tbl' for update in FROM clause

No comments:

Post a Comment