View Full Version : MySQL function
Pattons3rd
July 5th, 2007, 20:33
Hey I was just wondering if anyone knew of a MySQL function or alternate method to reference the last entry in a column of a database table?
I would appreciate any help.
And if anyone knows of something else I could do easier that would also help.
inimino
July 5th, 2007, 21:50
Actually, there is no "last entry" because data in a relational database is not ordered. Rows in a table may be returned in any order, and the order of rows in the database need not be preserved by SQL implementations. That is why a database "table" is actually a relation, not a table.
You can use an ORDER BY clause to impose an ordering on the returned results. You can use ORDER BY with LIMIT to return only the maximum value in a particular column. See the MySQL documentation for SELECT, where all of this is explained with examples.
Pattons3rd
July 6th, 2007, 02:42
Thanks for clearing that up, inimino.
So I have a database and all the rows are numbered.
All I really need is to find out the number of the last row so I can have the right number to insert for the next row.
I thought it might work to select the column with the numbers, store it in a variable, change it into an array, and use the PHP count() function to find out how many there are in the column, and then add 1 to it and store that into a variable to insert into the column with the next row.
Is this a good idea or should I do something else?
inimino
July 6th, 2007, 03:26
You should always use SQL features to query the database, since that's what SQL is for, rather than extracting more data than you need and doing extra processing.
In this case you can use an aggregate function, there's no need for LIMIT or ORDER BY. For a table 'table' with ID values stored in column 'row_id' you would simply use: SELECT max(row_id) FROM table;
Note that finding the maximum value is not the same as counting the number of rows.
Pattons3rd
July 6th, 2007, 14:33
Ok, I guess that makes sense.
Thanks so much for the help on this, I am just having problems with my database so I keep asking for help from people.
BennyP
July 16th, 2007, 14:56
An old post i know, but if it is just for numbering a new row, why not use autoincrement on the column so that each new row has a higher value than the last automatically.
Pattons3rd
July 16th, 2007, 15:48
Yeah, just yesterday I saw that column was Auto-Increment, but till then I didn't know what it meant.
So it is all sorted out now except for a connect to mysql problem which must be the host's fault.
vBulletin® v3.6.8, Copyright ©2000-2012, Jelsoft Enterprises Ltd.