简体   繁体   中英

Multiple entries for primary key

I'm working on this project wherein I need to add multiple entries for a primary key. I know using a primary key allows only one row but I need multiple entries for it. For an example:-

A customer having customer_id(primary key) 001 wants to buy two books of "_" quantity at a time. Since customer_id is a primary key and there are three columns in the backend: customer_id, book_name, quantity. How do I achieve this? The table looks like this:

customer_id book_name qty

001 java 2

After entering the first row details, I can't enter the second row as a duplicate primary key error occurs.

My error is related in the same way in a restaurant management system where I can't take multiple orders from a table_no as table_no is a primary key.

There are three tables: starters, main_course, drinks.

table_no(the common attribute), starter/maincourse/drink, qty.

table_no is the primary key in starter table and foreign keys in the main_course and drinks table. I can only add one-row data in each table for table_no say 1. And now I can't add more data in the following row for the same table no because duplication error occurs( due to primary key).

I'm sorry for the ill-defined structure of my problem. Thank you.

My design for this form

在此处输入图片说明

I think your database schema needs to be reevaluated.

You can only have one customer (customer entity) One customer can have multiple orders (order entity)

customer(
   customer_id PRIMARY KEY auto_increment,
   customer_name VARCHAR
   /* OTHER CUSTOMER SPECIFIC DETAILS */
)

book(
   book_id PRIMARY KEY auto_increment,
   book_name VARCHAR,
   book_isbn VARCHAR
   /* OTHER BOOK SPECIFIC DETAILS */
)

customer_order(
    order_id PRIMARY KEY auto_increment,
    customer_id FOREIGN KEY (customer_id) REFERENCES customer(customer_id)
)

customer_order_items(
    item_id PRIMARY KEY auto_increment,
    customer_order FOREIGN KEY(customer_id) REFERENCE customer_order(order_id)
    book_id FOREIGN KEY(book_id) REFERENCE book(book_id)
    quantity INT
)

So a customer can have many orders, a order can have many items, and order items can only have one item / book.

A primary key MUST be unique and can only ever be used exactly once in a single table but can be referenced many times.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM