【问题标题】:Why same query giving two different result?为什么相同的查询给出两个不同的结果?
【发布时间】:2012-06-22 22:25:48
【问题描述】:

我创建了两个表和插入的值,如下所示。

表 1

create table maxID (myID varchar(4));

insert into maxID values ('A001');
insert into maxID values ('A002');
insert into maxID values ('A004');
insert into maxID values ('A003');

表 2

create table maxID2 (myID varchar(4) PRIMARY KEY);

insert into maxID2 values ('A001');
insert into maxID2 values ('A002');
insert into maxID2 values ('A004');
insert into maxID2 values ('A003');

当我执行查询时

SELECT myId, @rowid:=@rowid+1 as myrow 
FROM maxID, (SELECT @rowid:=0) as init
ORDER BY myrow desc
LIMIT 1;

我得到的输出为

+++++++++++++
myid + myrow
+++++++++++++
A003 + 4
+++++++++++++

当我执行查询时

SELECT myId, @rowid:=@rowid+1 as myrow 
FROM maxID2, (SELECT @rowid:=0) as init
ORDER BY myrow desc
LIMIT 1;

我得到的输出为

+++++++++++++
myid + myrow
+++++++++++++
A004 + 4
+++++++++++++

两个表之间的区别在于,在第二个表中我的 myID 为PRIMARY KEY

您可以在www.sqlfiddle.com查看以上数据/结果。

我的问题是

为什么当查询相同时我得到两个不同的结果?

注意: 这个问题与我的旧问题 Getting last record from mysql 有点相关,我几乎得到了答案和牦牛告诉我行的顺序不能保证。 :(

【问题讨论】:

  • 嗯,正是因为 Yak 所说的:订单无法保证。这里底层表的顺序不同很可能是因为 InnoDB 表使用了基于主键的聚集索引。简单的答案是表格中的行顺序应该从不重要。

标签: mysql sql optimization indexing


【解决方案1】:

This is because when the selected fieldset is totally included into a given index fieldset, this index is used to retrieve the data instead of the fullscan result.

由于索引具有默认排序顺序,因此当原始表数据没有时,使用索引提取的数据显示的顺序与来自全表扫描的顺序不同。

在您的情况下,当您使用主键时,第 4 行确实是第 4 行,因为内部 mysql(oracle,sql server...)以这种方式组织它以更快地查找数据。

请注意,您可能偶然在两个查询中获得了相同的结果,只是因为默认选择的结果顺序确实没有被证明与插入的顺序相关。

最后,让我警告你,如果你计划在 mysql 中添加一个具有特定顺序的索引(如 here 描述的),以便以 DESC 顺序检索行,你不能这样做因为它在 mysql 中还不是一个允许的功能:

index_col_name 规范可以以 ASC 或 DESC 结尾。这些 未来扩展允许关键字用于指定升序 或降序索引值存储。目前,它们已被解析,但 忽略;索引值始终按升序存储。

【讨论】:

  • 完美....您能否在this问题上提供您的意见?
  • 嗯,但我不确定它是否代表对您的问题有价值的东西,对吗?您的问题的问题是没有肯定的答案:不,不可能仅从 mysql 核心中找出最后插入的行...
  • 是的,我看到了,但恐怕你不能这样做,除非你检查 mysql 的回滚日志是否可用:mysqlbinlog mysql-bin.000001
【解决方案2】:

Primary keys are returned in sorted order by default

这就是为什么两个查询会得到不同的输出。

您也可以查看另一个示例:here is the example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-11
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多