mysql 定义列 unique,MySQL将列定义为具有AUTO_INCREMENT的UNIQUE而不是主键

I'm working with a contract developer who is starting to create tables (MySQL) without define a Primary Key. Instead, he is defining a column with a UNIQUE constraint with an AUTO_INCREMENT. I've never seen this done before, so I wanted to understand the implications of defining tables this way. One downside would be not being able to create foreign keys if needed. What are some other implications, good or bad, of creating tables this way. Maybe I'm missing a concept here…

解决方案

Defining MySQL without explicit primary keys is a very very bad idea.

If a PK is missing, MySQL will create an implicit (but very real) integer autoincrementing primary key.

This PK will be included in every secondary key in InnoDB and will determine your primary sort order in MyISAM.

Consequence

You have just slowed down the performance of every select, insert and update.

For no purpose what so ever.

InnoDB: extra lookup required to get to table data

In InnoDB an extra lookup needs to be done, because all secondary indexes refer to the PK and not to the rows themselves.

MyISAM: wasted space

In MyISAM the penalty is not that great, but you're still dragging along a 4 byte unused field that doesn't get used.

InnoDB + MyISAM: Useless generation of autoincrement field

Because an implicit autoincrementing PK gets created, and you also needed a extra autoincrementing key to do joins; In order to prevent duplicate autoincrement fields, you now have not 1, but 2 table locks per insert.

InnoDB: with joins the lookup probem mentioned above doubles

If you do a join using a field that's not the PK, InnoDB needs to do an extra lookup per join to get to the records of that other table.

InnoDB: worst of all you lose the benefit of covering indexes

You have disabled one of the best optimizations in InnoDB, covering indexes.

If MySQL can resolve the query using only the data in the indexes, it will never read the table, this will result in a significant speed gain. Now that 50% of every index in InnoDB is unused space you have just nixed your chances of that optimization being used.

Please beat this contractor with a clue stick!

ib81c.png

BTW, if your contractor says, it does't matter much because he's using MyISAM, beat him again, you should always use InnoDB unless you have a good reason not too.

InnoDB is much much safer in production, MyISAM has its uses but gets corrupted too easily.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值