Foysal Vai
Foysal Vai

Reputation: 1363

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 ??

Upvotes: 0

Views: 354

Answers (2)

Andy Librian
Andy Librian

Reputation: 913

  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.

Upvotes: 1

Jimmy
Jimmy

Reputation: 304

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.

Upvotes: 0

Related Questions