mysql 查询 - 一起使用 in & order by 和 limit

标签 mysql sql

mysql 中运行查询时,得到一些奇怪的结果:

SQL 1:

 SELECT *
 FROM location
 WHERE name LIKE CONCAT('%','SZ','%')
   AND `STATUS` = 1
   AND location_level IN (4,3)
 ORDER BY location_level;

SQL 2:

 SELECT * 
 FROM location
 WHERE name LIKE CONCAT('%','SZ','%')
   AND `STATUS` = 1
   AND location_level IN (4,3)
 ORDER BY location_level
 LIMIT 2;

这 2 个 sql 之间的唯一区别是 Sql 2 有一个 limit 部分。

执行结果:

  • Sql 1 has 1 row,
  • Sql 2 has 0 rows

问题:

我期望 Sql 2 也应该得到结果,但它没有,知道吗?


@更新:

windows上的mysql好像很老了,我没能阻止它,好像死机了,所以我卸载了它,然后下载了mysql5.6,并安装了,现在2条sql都一样了。

很抱歉提出了无意义的问题。用mysql5.6现在就可以了。

最佳答案

我在 sqlfiddle.com 上试过了并得到了预期的结果,即 1。 我也浏览了 mySQL 文档并发现了以下内容

If you combine LIMIT row_count with ORDER BY, MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result.****(which in your case it should have return 1 if in somehow the result didn't gets changed in middle) If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found. After the initial rows have been found, MySQL does not sort any remainder of the result set

关于mysql 查询 - 一起使用 in & order by 和 limit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560291/

相关文章:

mysql - 如何连接三个表?计数和平均 SQL

sql - 如何插入包含撇号(单引号)的值?

mysql - 返回由sql语句动态查询的列名,以获取特定记录满足特定条件的列值

php - 出于角色目的,在每个 http 请求上使用现有表名创建 mysql View

php - 如何创建数组数据库行然后查找数组中是否存在值?

php - 限制 SQL 中的 unix 时间戳

sql - PostgreSQL。改善指标

sql - Postgresql,根据唯一字段从表中获取最新条目

php - 使用绑定(bind)参数时 mysqli 执行失败

为具有多项数据的用户设计Mysql