In MySQL's InnoDB storage engine, the primary key is typically auto-incremented. However, it is possible to auto-increment a non-primary key as well.
A database schema includes two tables: "book_comments" and "book_comments_votes." The "book_comments" table has a non-primary key column "comment_id" that needs to be auto-incremented for consistency with the "book_comments_votes" table, which contains a reference to "comment_id" as its primary key.
To auto-increment a non-primary key, it must be declared as an index. Here's an example:
CREATE TABLE `book_comments` (
`book_id` MEDIUMINT NOT NULL,
`timestamp` MEDIUMINT NOT NULL,
`user_id` MEDIUMINT NOT NULL,
`vote_up` SMALLINT,
`vote_down` SMALLINT,
`comment` TEXT,
`comment_id` MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`book_id`, `timestamp`, `user_id`),
KEY `comment_id` (`comment_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
While creating a simple index on the non-primary key is the most straightforward solution, some alternatives exist:
However, the recommended solution remains to create a unique index on the non-primary key and avoid the downsides of the alternatives. This approach provides both simplicity and integrity without sacrificing performance or data storage efficiency.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3