表(简体):
+---------------------------------------------------------------------+ | id (Primary AI) | user_id | status | type | data | ip | +=====================================================================+ | 1 | 3 | 0 | abc | a-s-d | - | +---------------------------------------------------------------------+ | 2 | 1 | 0 | ooo | z-z-z | - | +---------------------------------------------------------------------+ | 3 | 3 | 0 | ooo | f-f-f | - | +---------------------------------------------------------------------+ | 4 | 2 | 0 | abc | h-h-h | - | +---------------------------------------------------------------------+ | 5 | 1 | 0 | abc | a-s-d | - | +---------------------------------------------------------------------+更多信息:
ID是此表的主键(自动递增)
ID is the Primary Key of this table (Auto Increment)
请注意,我已将ID (Primary Key)用作新索引的第三个Seq_in_index
Please Note that i have used ID (Primary Key) as the 3rd Seq_in_index on new index
我已经为上述表格创建了一个综合索引
I have created a Composite Index for the mentioned table
CREATE INDEX userid_type_id ON table (user_id, type, id);
此索引中的id仅用于排序.
样本查询
SELECT id, status, data, ip FROM `table` WHERE user_id=3 AND type='abc' ORDER BY id DESC;我的问题是:
在复合索引中插入ID是一种好的(性能)做法吗?因为它仅用于ORDER BY
Is it a good (performance) practice to insert ID in the composite index? as it is only used for ORDER BY
在表的第一列时,可以使用ID(主键)作为索引中的第三个序列
Is it okay to use ID (primary key) as the third sequence in index while it is first column on the table
我是否根据样本查询正确选择了索引?
Did i choose my Index correctly based on my sample query?
我使用InnoDB
I use InnoDB
推荐答案答案取决于您使用的引擎:
Answer depends on engine you use:
- MyISAM-将ID添加到索引可以并且可能会有所帮助
- InnoDB-主键已经是每个二级索引的一部分,因为innodb将按主键排序的行存储在BTREE中,并且索引需要主键指向实际行-在这种情况下,如果它在索引中位于最后,则添加冗余(但这样做不会将其添加两次,因此它不会使情况变得更糟).在某些情况下,您可能希望将其添加为非最后一个,或者您拥有多列主数据库,并以不同的顺序向索引添加了一些列-这样做没有问题,innodb会将剩余的主列附加到该索引中,但可以使用之前添加的内容,而不必重复它们)
所以答案:
更多推荐
我们是否应该包括排序列,复合索引的主键(MySQL)
发布评论