gpt4 book ai didi

Mysql 强制我在多列唯一键的情况下创建多个索引

转载 作者:行者123 更新时间:2023-11-28 23:46:25 24 4
gpt4 key购买 nike

在下面的例子中:

table1 (id, f1, f2)

table2 (id, f3, f4)

related_table(id, table1_id, table2_id)

我有 2 个表和一个具有 HasAndBelongToMany 关系的相关表。(注意到我正在使用适合 ORM 的结构)。

当我使用两个外键创建多列索引时出现问题:

CREATE UNIQUE INDEX i1
ON related_table (table1_id, table2_id)

然后,我可以添加 table1_id 关系但无法添加 table2_id 关系。 Mysql 告诉我,我没有任何列 table2_id 的索引。这是为什么?

假设如果您创建一个多列索引,使用这个索引您可以按两个字段中的任何一个进行搜索。

最佳答案

这是mysql如何使用索引的结果。在关于 multiple-column indexes 的 mysql 文档中明确记载:

MySQL can use multiple-column indexes for queries that test all the columns in the index, or queries that test just the first column, the first two columns, the first three columns, and so on. If you specify the columns in the right order in the index definition, a single composite index can speed up several kinds of queries on the same table.

外键关系需要该字段的索引。对于 table1_id,您可以使用多列索引,因为 table1_id 是最左边的字段。对于 table2_id 不能使用多列索引,因为它不是最左边的字段。所以,不幸的是,如果你想正式创建 2 个表之间的关系,你需要在 table2_id 上创建一个单独的索引。

关于Mysql 强制我在多列唯一键的情况下创建多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com