简体   繁体   English

是否可以为主键和外键创建一个索引?

[英]Is it possible to create one index for both primary and foreign key?

Let's suppose we have two tables A and B and between them one-to-one relation.假设我们有两个表AB ,它们之间是一对一的关系。

CREATE TABLE IF NOT EXISTS A 
(
    ID INT UNSIGNED NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (ID)
);

CREATE TABLE IF NOT EXISTS B 
(
    ID INT UNSIGNED NOT NULL,
    PRIMARY KEY (ID),
    FOREIGN KEY (ID) REFERENCES A(ID)
        ON UPDATE CASCADE ON DELETE CASCADE
);

B.ID key will be used as foreign key in tables about which A doesn't know. B.ID键将用作A不知道的表中的外键。 When row is deleted from A there also will be deletion from other tables that are linked to B .当从A删除行时,也会从链接到B的其他表中删除。 As we see in B one column is at the same time primary and foreign key.正如我们在B中看到的,一列同时是主键和外键。 As I know keys use indexes.据我所知,键使用索引。 So, is it possible to make these two keys use the same index?那么,是否可以让这两个键使用相同的索引呢? Does it depend on RDBMS?它依赖于 RDBMS 吗? Or there is something wrong in my understanding?还是我的理解有问题?

As I know [foreign] keys use indexes据我所知 [foreign] 键使用索引

This is false.这是错误的。 I am guessing that your experience with databases is limited to MySQL/MariaDB.我猜你对数据库的经验仅限于 MySQL/MariaDB。 These are two databases where a foreign key definition does created an index on the referencing table.这是两个数据库,其中外键定义确实在引用表上创建了索引。

In most databases, a foreign key definition does NOT create an index on the referencing table.在大多数数据库中,外键定义不会在引用表上创建索引。 Another difference is that most databases (and I'm pretty sure the standard as well) requires that the referenced key be either a primary key or unique key.另一个区别是大多数数据库(我也很确定标准)要求引用的键是主键或唯一键。 That doesn't affect you in this case, but it is another deviation from the standard in MySQL in this area.在这种情况下,这不会影响您,但这是该领域 MySQL 中标准的另一个偏差。

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

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