mysql创建主键索引的关键字使用_MYSQL:创建表中的索引关键字以及何时使用它...

bd96500e110b49cbb3cd949968f18be7.png

What does index keyword mean and what function it serves? I understand that it is meant to speed up querying, but I am not very sure how this can be done.

When how to choose the column to be indexed?

A sample of index keyword usage is shown below in create table query:

CREATE TABLE `blog_comment`

(

`id` INTEGER NOT NULL AUTO_INCREMENT,

`blog_post_id` INTEGER,

`author` VARCHAR(255),

`email` VARCHAR(255),

`body` TEXT,

`created_at` DATETIME,

PRIMARY KEY (`id`),

INDEX `blog_comment_FI_1` (`blog_post_id`),

CONSTRAINT `blog_comment_FK_1`

FOREIGN KEY (`blog_post_id`)

REFERENCES `blog_post` (`id`)

)Type=MyISAM

;

解决方案

I'd recommend reading How MySQL Uses Indexes from the MySQL Reference Manual. It states that indexes are used...

To find the rows matching a WHERE clause quickly.

To eliminate rows from consideration.

To retrieve rows from other tables when performing joins.

To find the MIN() or MAX() value for a specific indexed column.

To sort or group a table (under certain conditions).

To optimize queries using only indexes without consulting the data rows.

Indexes in a database work like an index in a book. You can find what you're looking for in an book quicker, because the index is listed alphabetically. Instead of an alphabetical list, MySQL uses B-trees to organize its indexes, which is quicker for its purposes (but would take a lot longer for a human).

Using more indexes means using up more space (as well as the overhead of maintaining the index), so it's only really worth using indexes on columns that fulfil the above usage criteria.

In your example, the id and blog_post_id columns both uses indexes (PRIMARY KEY is an index too) so that the application can find them quicker. In the case of id, it is likely that this allows users to modify or delete a comment quickly, and in the case of blog_post_id, so the application can quickly find all comments for a given post.

You'll notice that there is no index for the email column. This means that searching for all blog posts by a particular e-mail address would probably take quite a long time. If searching for all comments by a particular e-mail address is something you'd want to add, it might make sense to add an index to that too.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值