简体   繁体   English

MySQL查询的顺序和限制

[英]MySQL query with order and limit

Assume data like: 假设数据如下:

table: shapes

id    type
----------------
1     Square
2     Rectangle
3     Square
4     Square

When I execute the following query: 当我执行以下查询时:

SELECT `shapes`.* FROM `shapes` WHERE `shapes`.`type` = 'Square' ORDER BY shapes.id DESC LIMIT 1

I would expect to receive a row with id: 4. Unexpectedly, I'm receiving a row with id: 1. 我希望收到ID为4的行。出乎意料的是,我收到ID为1的行。

For the really strange part: If I execute the same query with LIMIT 2 : 对于真正奇怪的部分:如果我使用LIMIT 2执行相同的查询:

SELECT `shapes`.* FROM `shapes` WHERE `shapes`.`type` = 'Square' ORDER BY shapes.id DESC LIMIT 2

The first row in that set of 2 is actually the correct row! 该2组中的第一行实际上是正确的行!

And to add to the strangeness still, I have another copy of this database within the same MySQL server, and it returns the correct row for any limit query, LIMIT 1 or otherwise. 更让人感到奇怪的是,我在同一台MySQL服务器中有该数据库的另一个副本,它为任何限制查询( LIMIT 1或其他)返回正确的行。

The only answer I can come to is to dump and reload the database, but I'd like to understand why this is happening first before taking that action, if possible. 我唯一能想到的答案就是转储并重新加载数据库,但是我想理解为什么在可能的情况下首先采取这种行动。

tl;dr: LIMIT 1 returns the wrong row. tl; dr: LIMIT 1返回错误的行。 LIMIT 2 returns the correct row (for the first one). LIMIT 2返回正确的行(对于第一行)。 Seems to be database specific. 似乎是特定于数据库的。

The problem is caused as you are not using limit 0, 1. While not provided the full query sometimes it display wrong results. 由于您没有使用限制0、1而导致此问题。虽然未提供完整查询,但有时显示错误结果。 I suggest you to type/execute the full query. 我建议您键入/执行完整的查询。

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

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