Pro*_*ist 29 mysql innodb primary-key
是否可以自动增加非主键?
表"book_comments"
book_id medium_int
timestamp medium_int
user_id medium_int
vote_up small_int
vote_down small_int
comment text
comment_id medium_int
Primary key -> (book_id, timestamp, user_id)
Run Code Online (Sandbox Code Playgroud)
此表上没有其他索引.但是,我想使comment_id列自动增量,以便我可以轻松地创建另一个表:
表"book_comments_votes"
comment_id (medium_int)
user_id (medium_int)
Primary key -> (comment_id, user_id)
Run Code Online (Sandbox Code Playgroud)
用户只能在每次评论时投票一次.此表通过主键强制执行此规则.
题:
是否可以自动递增非主键 - 例如,自动递增comment_id表"book_comments"中的列?
替代方案,讨论:
如上所述,我想简单地这样做.替代方案并不乐观.
book_id, timestamp, user_id.在这种情况下,我会创建一个额外的索引.book_comments_votes整个PK中的comment_id .这将超过表格的三倍.建议?思考?
Dan*_*ack 41
是的你可以.您只需要将该列作为索引.
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'
);
Run Code Online (Sandbox Code Playgroud)
将为'testInc'插入具有自动递增值的行.然而,这是一件非常愚蠢的事情.
你已经说过正确的方法:
"通过book_id,timestamp,user_id上的唯一索引创建comment_id PK并强制执行完整性."
这正是你应该这样做的方式.它不仅为您提供了适合您未来查询所需的主键,还满足了最不惊讶的原则.
| 归档时间: |
|
| 查看次数: |
30288 次 |
| 最近记录: |