简体   繁体   English

MySQL索引定义,有什么区别?

[英]MySQL index definitions, whats the difference?

What is the difference between these two indexes? 这两个指标有什么区别? I'm referring to the difference between both columns being under the 'PRIMARY' and the other way.. 我指的是“PRIMARY”下的两列之间的差异以及另一种方式。

在此输入图像描述

在此输入图像描述

第一个意味着组合user_id, wallet_type是唯一的,第二个意味着只将visitid定义为唯一。

The first one is known as a multi-column, compound, or composite key. 第一个称为多列,复合或复合键。 In this case, the primary key constraint is the combination of the two columns, in the listed order (user_id, then wallet_type). 在这种情况下,主键约束是列出的顺序中的两列的组合(user_id,然后是wallet_type)。 The two columns, combined, must be unique for each row. 组合的两列对于每一行必须是唯一的。

So, the following data is okay: 所以,以下数据是可以的:

user_id(pk)  wallet_type(pk)
-------------------------
1            1
1            2
2            2

Notice that rows can have duplicate user_id's or wallet_type's, but not both: 请注意,行可以包含重复的user_id或wallet_type,但不能同时包含:

user_id(pk)  wallet_type(pk)
-------------------------
1            1
1            2
2            2
1            1      // Duplicate key

The second example is just a regular single-column key, where the just value in the visitid column must be unique: 第二个示例只是一个常规的单列键,其中visitid列中的just值必须是唯一的:

visitid(pk)    session
-------------------------
1              1
1              2   // Duplicate key

There are many implications with this. 这有很多含义。

The multi-column primary key is larger, so it uses more storage and is slightly slower for MySQL to traverse. 多列主键较大,因此它使用更多存储空间,而MySQL的遍历速度稍慢。

Also, with InnoDB, inserts are negatively affected because primary keys are clustered indexes, which means they are stored in physical order. 此外,对于InnoDB,插入受到负面影响,因为主键是聚簇索引,这意味着它们以物理顺序存储。 A larger index takes longer to update. 更大的索引需要更长时间才能更新。 Appending rows to the end is fine, however. 然而,将行追加到最后是好的。

There are some benefits, such as the ability to use the multi-column index as a covering index. 有一些好处,例如使用多列索引作为覆盖索引的能力。

For example, the following queries would be optimized with the multi-column primary key: 例如,将使用多列主键优化以下查询:

SELECT user_id, wallet_type FROM table1 WHERE user_id = 1
SELECT user_id, wallet_type FROM table1 WHERE user_id = 1 AND wallet_type = 2
SELECT user_id, wallet_type FROM table1 ORDER BY user_id, wallet_type
SELECT user_id, wallet_type FROM table1 WHERE user_id = 1 ORDER BY wallet_type
SELECT user_id, wallet_type FROM table1 WHERE user_id > 1 AND wallet_type > 2
SELECT user_id, wallet_type FROM table1 ORDER BY user_id, wallet_type

However, since columns are left prefixed, this query would not be optimized: 但是,由于列保留了前缀,因此不会优化此查询:

SELECT user_id, wallet_type FROM table1 WHERE wallet_type = 2

This is because user_id is not referenced in the WHERE clause, but user_id is the first column in the key. 这是因为WHERE子句中未引用user_id,但user_id是键中的第一列。 You can't skip a column. 你不能跳过一列。

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

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