简体   繁体   English

插入具有自动增量ID的新行未添加为数据库中的最后一个条目

[英]insert new row with auto incremental id is not added as last entry in the database

I have a SQL - MyIsam table called links with the following structure 我有一个SQL-MyIsam表,称为具有以下结构的links

| field      | type         | null | predefined       | extra          |
|------------|--------------|------|------------------|----------------|
| id         | int(11)      | no   | none             | auto_increment |
| link       | varcar(2083) | no   | none             | none           |
| created_at | timestamp    | no   | curret_timestamp | none           |
| origin     | varcar(100)  | no   | none             | none           |

my insert statement is 我的插入声明是

public function createLink($user_id, $link, $origin) {        
        $stmt = $this->conn->prepare("INSERT INTO links(link, origin) VALUES(?,?)");
        $stmt->bind_param("ss", $link, $origin);
        $result = $stmt->execute();
        $stmt->close();

        if ($result) {
            // link row created
            // now assign the link to user
            $new_link_id = $this->conn->insert_id;
            $res = $this->createUserLink($user_id, $new_link_id);
            if ($res) {
                // link created successfully
                return $new_link_id;
            } else {
                // user_link failed to create
                return NULL;
            }
        } else {
            // link failed to create
            return NULL;
        }
    }

unfortunately sometimes i get an unexpected behavior which i'm not totally able to reproduce. 不幸的是,有时我会得到一个意想不到的行为,我不能完全复制。

链接表

as you can see the rows with id 301 and 304 has been inserted between 286 and 293 as well as row with id 300 is between 298 and 296. 正如您所见,已在286和293之间插入ID为301和304的行,以及ID为300的行在298和296之间。

Since id is auto incremental, i would have expected to find all of them ordered from the smaller to the higher value. 由于id是自动增量的,我本来希望找到从较小值到较高值的所有序列。

This is bad for my application because i need that the chronological order of creation is respected and followed whenever i query the db to get all the links 这对我的应用程序来说很糟糕,因为我需要遵循创建的时间顺序,每当我查询数据库以获取所有链接时都会遵循

 public function getAllUserLinks($user_id) {
        $stmt = $this->conn->prepare("SELECT l.* FROM links l, users_links ul WHERE l.id = ul.link_id AND ul.user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $links = $stmt->get_result();
        $stmt->close();
        return $links;
    }

i know i could add an ORDER BY... to my query but this would further slow down things. 我知道我可以在我的查询中添加ORDER BY...但这会进一步降低速度。

Besides, new links should be added as last row of the table, not in the middle , right?!? 此外,新的链接应该作为表的最后一行添加,而不是在中间,对吧?

So the physical order you see will be down to your clustered index, if you haven't defined one then MySQL will do it for you, from the InnoDB docs here : 所以你看到的物理顺序将归结为你的聚集索引,如果你还没有定义一个,那么MySQL会为你做这个,来自这里的InnoDB文档:

If the table has no PRIMARY KEY or suitable UNIQUE index, InnoDB internally generates a hidden clustered index on a synthetic column containing row ID values. 如果表没有PRIMARY KEY或合适的UNIQUE索引,InnoDB会在包含行ID值的合成列内部生成隐藏的聚簇索引。 The rows are ordered by the ID that InnoDB assigns to the rows in such a table. 行按InnoDB分配给此类表中的行的ID排序。 The row ID is a 6-byte field that increases monotonically as new rows are inserted. 行ID是一个6字节的字段,随着新行的插入而单调增加。 Thus, the rows ordered by the row ID are physically in insertion order. 因此,由行ID排序的行在物理上处于插入顺序。

I'm assuming you're using InnoDB but MyISAM would also use the clustered index to determine physical order. 我假设您正在使用InnoDB,但MyISAM也会使用聚集索引来确定物理顺序。 Some more info here about clustered indexes. 一些更多的信息在这里有关聚簇索引。

Edit 编辑

The comment below is correct to say clustered indexes are how data is stored and strictly speaking not how data is retrieved. 下面的评论是正确的,说聚集索引是数据的存储方式,严格来说不是如何检索数据。 In practice there's a good chance you'll find data returned in physical order if you don't specify an ORDER BY. 实际上,如果您未指定ORDER BY,则很有可能找到按物理顺序返回的数据。

I was attempting to explain why the questioner might be seeing the ordering he was but I'm not saying this should be relied upon, no guarantees are given about the order of data without an ORDER BY. 我试图解释为什么提问者可能会看到他的顺序,但我并不是说这应该被依赖,没有ORDER BY就没有关于数据顺序的保证。 From the SQL 92 spec (in various places): SQL 92规范 (在各个地方):

If an is not specified, then the ordering of the rows of Q is implementation-dependent 如果未指定a,则Q行的排序依赖于实现

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

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