简体   繁体   English

MySQL,外键与索引 ID 列不为空

[英]MySQL, Foreign Key vs Indexed ID column with NOT NULL

Lets say you have Users table and Posts table.假设您有用户表和帖子表。

Users用户

id
name
email

Posts帖子

id
contents
user_id

If I add index to "user_id" in Posts table, and set it as NOT NULL, Can I expect same effect as Foreign Key?如果我在 Posts 表中为“user_id”添加索引,并将其设置为 NOT NULL,我可以期待与外键相同的效果吗?

I know that I can set user_id as any number, whereas foreign_key will force you set valid id.我知道我可以将 user_id 设置为任何数字,而 foreign_key 会强制你设置有效的 id。 Let's assume that user_id is valid.假设 user_id 是有效的。 Is there any performance benefit when we set foreign_key?当我们设置foreign_key时有什么性能优势吗?

The main benefit of foreign keys is that they enforce data consistency, meaning that they keep the database clean in other words Keys are Indexes that have Integrity rules applied to prevent corruption of data.外键的主要好处是它们强制数据一致性,这意味着它们保持数据库清洁,换句话说,键是应用了完整性规则以防止数据损坏的索引。

Index is a data structure built on columns of a table to speed up search for indexed records based on values of indexed columns.索引是一种建立在表列上的数据结构,用于根据索引列的值加快搜索索引记录的速度。 In other words you gain search speed in exchange of insert/delete speed and storage.换句话说,您获得搜索速度以换取插入/删除速度和存储。

Is there any performance benefit when we set foreign_key?当我们设置foreign_key时有什么性能优势吗?

In performance terms, you will face no improvement.在性能方面,您不会面临任何改进。

Foreign keys will impact INSERT, UPDATE and DELETE statements because of the data checking rules , but keep in mind that your data will be consistet .由于数据检查规则,外键会影响 INSERT、UPDATE 和 DELETE 语句,但请记住,您的数据将是一致的。

In MySQL, defining a foreign key constraint automatically creates an index, unless it can use an index that already exists.在 MySQL 中,定义外键约束会自动创建索引,除非它可以使用已经存在的索引。 That is, if you create an index and subsequently add a foreign key on the same column(s), MySQL does not create an extra index just for the foreign key.也就是说,如果您创建索引并随后在同一列上添加外键,MySQL 不会仅为外键创建额外的索引。

If you run a query that needs that index, it doesn't matter if you created the index yourself or if the index was created as a side-effect of adding the foreign key.如果您运行需要该索引的查询,则无论您是自己创建索引还是创建索引作为添加外键的副作用都没有关系。 Either way, the index can help the query.无论哪种方式,索引都可以帮助查询。 The performance benefit is the same.性能优势是相同的。

If you run a query that does not need that index, then there's no benefit to having index either way.如果您运行不需要该索引的查询,那么无论哪种方式都有索引都没有好处。

You didn't describe any specific SQL query, so there's no way for us to guess whether the index is needed.您没有描述任何特定的 SQL 查询,因此我们无法猜测是否需要索引。

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

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