MySql `id` column has a 'PRIMARY' and a 'UNIQUE' index, is this ideal?

时间:2016-02-12 22:03:31

标签: mysql performance indexing unique

Everything I can find on the internet explains the difference between these types of indexing, that is NOT my question.

When I create a new table in a database, I always create an id primary key as I'm sure most people do. I always make it $timeout( function() { $scope.setFocus('name', $scope.users.length - 1); }, 50); $scope.setFocus = function (id, index) { angular.element( document.querySelectorAll("#" + id))[index].focus(); }; .

I'm recently getting big into adding custom indexes and I've noticed that my id field has these two index's (automatically created, for obvious reasons):

PRIMARY KEY, NOT NULL, UNIQUE, AUTO_INCREMENT

My assumption is due to the PK flag (primary key) the 'PRIMARY' index was automatically generated, and due to the There is a PRIMARY index There is also a UNIQUE index flag the 'UNIQUE' index was created.

I assume having two indexes on the same column is adding unnecessary overhead. My question is, is this true? Should I remove one of these index's? Or is it normal/ideal to have both of these index's created on my id column?

1 个答案:

答案 0 :(得分:1)

PRIMARY KEY(x), UNIQUE(x) - 由于PRIMARY KEY 定义(在MySQL中)UNIQUE,因此后一索引是多余的,应该删除。

此外,在UNIQUE(x), INDEX(x)中,INDEX(x)是多余的。

冗余索引占用额外空间。 (在未来的版本中,它们甚至可能被禁止 - 这就是它们无用的。)

每张桌子应该(或者甚至"必须")有PRIMARY KEY。它可以是AUTO_INCREMENT,也可以是某些"自然"键。 "天然"从某种意义上说它是UNIQUE而永远不是NULL。在一项简短的调查中,我发现只有25%的表格有AUTO_INCREMENT列。

More on indexing

不要忘记考虑"复合"索引,例如INDEX(a,b)