且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL InnoDB:自增非主键

更新时间:2023-02-03 08:24:54

是的,你可以.您只需将该列设为索引即可.

Yes you can. You just need to make that column be an index.

CREATE TABLE `test` (
  `testID` int(11) NOT NULL,
  `string` varchar(45) DEFAULT NULL,
  `testInc` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`testID`),
  KEY `testInc` (`testInc`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


insert into test(
  testID,
 string
)
values (
1,
    'Hello'
);


insert into test( 
testID,
 string
)
values (
2,
    'world'
);

将为testInc"插入具有自动递增值的行.然而,这是一件非常愚蠢的事情.

Will insert rows with auto-incrementing values for 'testInc'. However this is a really dumb thing to do.

你已经说过正确的方法了:

You already said the right way to do it:

通过 book_id、timestamp、user_id 上的唯一索引使 comment_id PK 并强制执行完整性."

"Make the comment_id PK and enforce integrity through a unique index on book_id, timestamp, user_id."

这正是你应该做的.它不仅为您提供将来查询所需的表的正确主键,还满足 最小惊讶原则.

That's exactly the way that you should be doing it. Not only does it provide you with a proper primary key key for the table which you will need for future queries, it also satisfies the principle of least astonishment.