SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast St. Anger's Avatar
    Join Date
    Nov 2003
    Location
    R'lyeh
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Add MySQL entry with MAX(column) + 1

    I'm trying to do something pretty simple, but can't seem to get it right. I want to do this with an insert statement:

    Code:
    INSERT INTO pages SET pageorder = MAX(pageorder) + 1;
    But that doesn't work... This works though:

    Code:
    SELECT @newPageOrder := MAX(pageorder) + 1 FROM pages;
    INSERT INTO pages SET pageorder = @newPageOrder;
    The trouble with that is that I want to insert multiple entries and think it seem ineffiecient to have to use a select statement for each entry. Why can't I just use pageorder = MAX(pageorder) + 1?

  2. #2
    SitePoint Evangelist
    Join Date
    Aug 2007
    Posts
    566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    insert into pages (pageorder)
    select max(pageorder) + 1
    from pages;
    This should be ok.

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,347
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    the real question here, of course, is why aren't you using auto_increment?
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Enthusiast St. Anger's Avatar
    Join Date
    Nov 2003
    Location
    R'lyeh
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by r937 View Post
    the real question here, of course, is why aren't you using auto_increment?
    I was using it for the ID field, can I use it for the pageorder field too? The ID is the primary key, the pageorder controls the order that pages are displayed in, which can be changed by the user.

    I tried changing the column type:

    Code:
    ALTER TABLE pages CHANGE pageorder pageorder INT NOT NULL AUTO_INCREMENT;
    But got this error:

    #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

    Thanks for the help guys

  5. #5
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,347
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    ummmmm....

    you may find it difficult to assign new ID values now

    a table can have only one auto_increment
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •