简体   繁体   English

为什么SQL查询的结果不会按照我期望的顺序返回?

[英]Why do results from a SQL query not come back in the order I expect?

如果将项目插入表中,然后我编写一个查询,例如select * from table ,为什么结果不符合我的预期?

The order of a query can be forced by using an 'Order by' Clause in the statement. 可以使用语句中的“Order by”子句强制查询的顺序。 A SQL Database does not actually understand what order you put things in, or store the data in a given order. SQL数据库实际上并不了解您放入内容的顺序,或以给定顺序存储数据。 This means that you need to tell SQL what order you want the items in. For instance: 这意味着您需要告诉SQL您希望项目的顺序。例如:

Select * from Table
  order by column1 desc

Think about it like handing some stuff to your friend to hold - she will have all of it for you later, but she stores it someplace in the mean time. 想想就像将一些东西交给你的朋友一样 - 她将在以后为你提供所有这些东西,但她会在同一时间将它存放到某个地方。 She may move it around while you are not looking to make room for something else, or may hand it back in the same order you gave it to her, but you didn't tell her to keep it in order, so she doesn't. 当你不打算为其他东西腾出空间时,她可能会移动它,或者可能按照你给她的顺序将它移回去,但是你并没有告诉她要保持顺序,所以她没有。

Databases need to be able to move things around in the background, so the way they are built does not intrinsically know about any order - you need to know the order when you give it to the database, so that you can put it back in the order you want later. 数据库需要能够在后台移动,因此它们的构建方式本质上不知道任何顺序 - 当您将数据提供给数据库时需要知道顺序,以便您可以将其放回到数据库中。你想要的订单。 The order clause allows SQL to impose an order on the data, but it doesn't remember or have one on its own. order子句允许SQL对数据强加一个顺序,但它不记得或者有一个单独的数据。

Important point : Even when SQL returned the items in the correct order without an order by statement the last 1 million times, it does not guarantee that it will do so. 重要的一点 :即使SQL在没有order by语句的情况下以正确的顺序返回项目的最后100万次,也不能保证它会这样做。 Even if a clustered index exists on the table, the results are not guaranteed to be returned in the order you expect. 即使表上存在聚簇索引,也不能保证按预期的顺序返回结果。 Especially when SQL versions change, not explicitly using an order by clause can break programs that assume the query will be in the order they want! 特别是当SQL版本发生更改时,未明确使用order by子句可能会破坏假定查询将按其所需顺序排列的程序!

It is a common misconception to expect results in the order that is inserted. 期望按插入顺序得出结果是一种常见的误解。 Even when a clustered index is used, the result set may not be as expected. 即使使用聚簇索引,结果集也可能不符合预期。 Only way to force an order is to use an "order by" clause. 强制执行订单的唯一方法是使用“order by”子句。 The reason that the order is different from what is expected may vary. 订单与预期不同的原因可能会有所不同。 The query may be executed in parallel and the result set may be merged or it may be due to the query optimization plan while trying to return the result set as fast as possible. 查询可以并行执行,并且结果集可以合并,或者可以归因于查询优化计划,同时尽可能快地返回结果集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM