I have a table with books, there can be multiple copies of each book and I want to give each copy a copy number.
TABLE:
BOOK(book_pk, book_name, book_copy);
Basically each book_pk will be unique, but if there are two rows with the same book_name, one book_copy should be set to 1, and the other set to 2.
TABLE ROWS:
1, AAA, 1
2, BBB, 1
3, AAA, 2
4, CCC, 1
5, BBB, 2
So I want to auto-increment the primary key and keep track of the copyNumber as I insert new tuples of the same book_name.
Try:
INSERT INTO Book (book_name, book_copy)
VALUES (
'AAAA',
(SELECT copy FROM ( SELECT IFNULL(MAX(book_copy),0)+1 as copy FROM Book) AS d)
);
The short version is that in MySQL it can't be done directly from the database. Perhaps this is best described with two tables. A Book
table and a BookCopy
table. The Book
table can have an auto increment just as you have. The BookCopy
table also has an auto increment but references back to the Book
table. This way you can have a Book for which you have no copies, and you can't have a BookCopy
for an unindetified Book
.
Book Table
Book(book_pk (auto increment), book_name, ...)
BookCopy Table
BookCopy(book_copy_pk (auto increment), book_pk (foreign key), ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.