Drawbacks of Composite Primary Keys

Bad case: In the design process of the activity_spring_red_packet_sync table, the three columns of id, user_id, and date are used as a composite primary key.
What is wrong with the above situation?

One, sql statement

CREATE TABLE `activity_spring_red_packet_sync` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `phone` char(15) NOT NULL COMMENT '用户手机号',
  `date` date NOT NULL COMMENT '发送日期',
  `remain_send_times` int(11) NOT NULL COMMENT '剩余可发红包次数',
  `remain_get_times` int(11) NOT NULL COMMENT '剩余领取红包次数',
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`,`user_id`,`date`),
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1 COMMENT='春节活动收发红包次数';

2. Problem analysis

  • What is a joint index, and what is the difference between a composite index?
  1. When two data tables form a many-to-many relationship, you need to form a joint primary key through the primary keys of the two data tables to determine one of the records in each data table
  2. In a data table, multiple fields are used as the primary key to determine a record. Then, multiple fields form a composite primary key.
  • Disadvantages of composite primary key?
  1. If there are frequent business modifications, the primary key information in the non-clustered index will be modified accordingly, and it will easily cause the physical movement of records in the table.
  2. Fields with business meaning need to be generated according to certain rules, and string types such as varchar are unavoidable, which affects insertion and query efficiency.
  3. Changes in business rules can easily expand the impact.

3. Solve the problem

  • What is needed is to use the user and date as a unique identifier;
  • Utilize index UNIQUE KEY
PRIMARY KEY (`id`),
UNIQUE KEY `SPRING_RED_PACKET_USER_DATE_IDEX` (`date`,`phone`) USING BTREE

Guess you like

Origin blog.csdn.net/CUG_ZG/article/details/87691663