简体   繁体   中英

MySql - One to Many Relationship

How to maintain One to Many Relationship in database ?? Which is the appropriate process??

Like, I am inserting library information from a form. Library name,library description,library address fields are in text boxes. There is a group of check boxes which are representing which books are available in that library. Assume I have three table 'library','books','library_book_relation'.

In this secenerio, Which is the exact process ??Do I have to insert data into two tables (library,library_book_relation) with 2 query like 1. insert to into library .... and 2. insert to into library_book_relation .... simultaneously, Or there is any other method to do the job ??

What I'll have to do (query) when I would like to retrieve library information from database ?? Which method does software world follow ??

  1. You need to insert your data to library table
  2. After inserting new row, you will get the last id inserted in your library table
  3. Insert your library books (relation) using your last id as a foreign key to library table

Don't forget to wrap all aforementioned steps inside a transaction.

You will have to enter data in both the tables one after the other.

First insert the library record.

Second insert the books and library record in the mapping table.

For retrieving you can use joins to retrieve libraries and their corresponding books.

Ex. Select * from library inner join library_books_relation on library.lib_id=library_books_relation.lib_id where lib_id=something

Or you can retrieve all the records by removing the 'where' clause.

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