MySQL TOP 和 ORDER BY sql 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11076568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:51:25  来源:igfitidea点击:

TOP and ORDER BY sql error

mysqlsql

提问by markasoftware

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:

我正在尝试使用 PHP 从 MySQL 的表中选择最后一条记录。我相信我有一个 SQL 错误。这是我的 SQL 代码:

SELECT TOP 1 id FROM `table` ORDER BY id DESC

If this is valid and I actually have a PHP error, tell me.

如果这是有效的并且我实际上有一个 PHP 错误,请告诉我。

回答by John Woo

you have an invalid sql syntax. use LIMITinstead

您的 sql 语法无效。使用LIMIT代替

try this:

尝试这个:

SELECT id 
FROM table 
ORDER BY id DESC
LIMIT 1

the TOPclause works on MSSQL server.

TOP子句适用于 MSSQL 服务器。

回答by Zane Bien

A simpler and more DBMS-agnostic approach would be:

一种更简单且与 DBMS 无关的方法是:

SELECT MAX(id) AS id
FROM table

That's only if you want justthe idfield, otherwise if you tried to SELECT other columns, it wouldn't return matching data to the idfield and you would instead have to use:

这是唯一的,如果你想刚刚id领域,否则,如果您想选择其它列,它不会返回数据匹配到id现场,你会反而不得不使用:

SELECT id, otherfields, ..., ...
FROM table
WHERE id = (SELECT MAX(id) FROM table)

回答by Faizal R

This will work To find the last record if you are not looking to use limit

如果您不想使用限制,这将起作用以查找最后一条记录

SELECT TOP 1 * FROM Products ORDER BY id desc

This will work To find the last record specifying column name if you are not looking to use limit

如果您不想使用限制,这将起作用以查找指定列名的最后一条记录

SELECT TOP 1 id FROM Products ORDER BY id desc

Else

别的

SELECT * FROM Products ORDER BY id DESC LIMIT 1