mysql - 外键索引

标签 mysql performance indexing foreign-keys

使用 MySQL。我有 2 张基本的 child table 和团体 table 。两者都是直截了当的。 child :身份证、名字、姓氏。组:id、名称。一个 child 可以属于 0 到多个组。一个组可以包含 0 到多个子项。这是在第三个表中处理的:子组。我已向子级和组添加了外键。

CREATE TABLE childgroups 
(
    childId INT,
    groupId INT
);

ALTER TABLE childgroups 
    ADD FOREIGN KEY (fk_child) REFERENCES children(id);
ALTER TABLE childgroups 
    ADD FOREIGN KEY (fk_group) REFERENCES groups(id);

由于外键不会自动建立索引,因此我想在子组表上创建索引。

我将在此表上使用如下语句:

SELECT childId 
FROM childgroups 
WHERE groupId = 123;

SELECT groupId 
FROM childgroups 
WHERE childId = 1366;

SELECT children.firstname, children.lastname 
FROM children, childgroups, groups 
WHERE groups.name = "Lions";

仅在 childId 和/或 groupId 上定义索引就足够了吗?

或者我还指定一个组合索引,例如:

CREATE INDEX childgroups_index ON childgroups (childid);
CREATE INDEX childgroups_index ON childgroups (groupid);
CREATE INDEX childgroups_index ON childgroups (childid, grouppid);

最佳答案

您关于外键不会自动索引的假设是不正确的,请参阅 Using FOREIGN KEY Constraints :

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

但是,您的表在 (childId, groupId) 上缺少唯一键,否则,您将被允许多次添加相同的组合。因此,最好将这两列设置为(复合)主键(这对于关联表来说很常见):

CREATE TABLE childgroups 
(
    childId INT,
    groupId INT,
    primary key (childId, groupId)
);

除了groupId上的外键生成的隐式索引(childId上的外键可以使用主键)之外,你能想到的每一个索引需求满足,并且您不需要在该表上添加任何其他索引。

关于mysql - 外键索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58171176/

相关文章:

sql-server - 重建索引不会更改非聚集索引的碎片百分比

indexing - 在not_analyzed字段的中间搜索

Mysql触发器创建失败

performance - haskell : matrix sorting much slower than vector sorting

javascript - 无法使用sequelize和mysql根据包含的模型属性过滤数据

c++ - 为什么编译需要这么长时间?

php - 在 PHP 中使用正则表达式作为请求处理程序是否不好?

在 Lucene 中索引标记二元组

python - 使用 MySQL 从 Django QuerySet 获取不同的值

MySql Sum with Case 查询输出另一个表