I am trying to select the last record from a table in MySQL using PHP. I believe I have an SQL error. Here is my SQL code:
SELECT TOP 1 id FROM `table` ORDER BY id DESC
If this is valid and I actually have a PHP error, tell me.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.
There is an alternative to TOP clause, which is to use ROWCOUNT. Use ROWCOUNT with care, as it can lead you into all sorts of problems if it's not turned off.
it simply means sorting the view or table by 1st column of the query's result.
you have an invalid sql syntax. use LIMIT instead
try this:
SELECT id FROM table ORDER BY id DESC LIMIT 1
the TOP
clause works on MSSQL server.
A simpler and more DBMS-agnostic approach would be:
SELECT MAX(id) AS id FROM table
That's only if you want just the id
field, otherwise if you tried to SELECT other columns, it wouldn't return matching data to the id
field and you would instead have to use:
SELECT id, otherfields, ..., ... FROM table WHERE id = (SELECT MAX(id) FROM table)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With