如何判断从MYSQL数据库读取数据的顺序?
有没有办法改变从数据库读取数据的顺序?您知道,默认顺序是从插入的第一个数据到最新的数据读取它们,那么有没有办法将其更改为最新->第一个?
is there a way to change the order data from a DB are read ? you know , the default order is that they are read from the first data inserted to the latest so is there a way to change it to latest->first?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
,否,这是不正确的。默认顺序取决于很多因素,不同的执行计划可能会导致不同的顺序。如果不使用 ORDER BY,则顺序是不确定的。这意味着您不应依赖它按插入顺序返回行,因为情况并非总是如此。
如果您想依赖订单,则必须添加 order by 子句。如果您想先返回最近插入的行,然后添加一列
insert_date
,请在插入时使用值NOW()
并将其添加到您的查询中:正如其他人也有的那样指出,如果你有一个自动递增的主键,那么你可以按它来排序。
No, this is not correct. The default order depends on a lot of things and different execution plans can result in different orders. If you do not use an ORDER BY the order is indeterminate. This means you should not rely on it returning rows in insert order as this won't always be the case.
If you want to rely on the order you must add an order by clause. If you want to return the rows most recently inserted first then add a column
insert_date
, use the valueNOW()
when inserting and add this to your query:As others have also pointed out, if you have an auto-incrementing primary key then you could order by that.
您无法更改默认排序方式。这种行为甚至不是由服务器指定的,而是由表引擎指定的。
例如,无论您插入
InnoDB
中的顺序如何,它始终会采用PRIMARY KEY
上的默认顺序,这与MyISAM
的行为不同You cannot change the default order-by. This behavior is not even specified by the server, it is specified by the Table Engine.
For example, no matter what order you insert into
InnoDB
, it will always default order on thePRIMARY KEY
, which is different behavior thanMyISAM
将时间戳列添加到您的表中(或者如果您的 ID 自动递增,您也可以使用它)并执行
ORDER BY DESC
。默认情况下的顺序应该被认为是任意的。在向用户显示数据时,最好始终使用
ORDER BY
以避免混淆。Add a timestamp column to your table (or if your ID auto-increments, you could also use that) and do
ORDER BY DESC
.The order things come in by default should be considered arbitrary. It's a good idea to always use
ORDER BY
when displaying data to users to avoid confusion.正如其他人指出的:在您的 sql 语句中使用“ORDER BY”,尽管您的数据集需要一个时间戳字段,该字段将在添加新数据集时使用当前日期/时间进行设置。
然后,您应该能够从第一个到最后一个或从最后一个到第一个对数据进行排序(ORDER BY myTimestampField DESC)
As others pointed out: 'ORDER BY' in your sql statement, though your datasets will need a timestamp field which is to be set with the current Date/time when new datasets are added.
You should then be able to order your data from first to last, or from last to first (ORDER BY myTimestampField DESC)
SELECT * FROM {tablename} ORDER BY id DESC
上面假设您有一个 ID 字段,该字段随着每次插入而递增。您还可能有一个可在 ORDER BY 语句中使用的“CreateDate”类型字段。
ORDER BY 默认为升序,因此要获取最新 -> 第一个,请使用 DESC。
SELECT * FROM {tablename} ORDER BY id DESC
The above assumes you have an ID field that is incremented with each insert. You may also have a 'CreateDate' type field that you can use in the ORDER BY statement.
ORDER BY will default to an ascending order, so to get latest->first, use DESC.