简体   繁体   English

MySql-一对多关系

[英]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'. 假设我有三个表“ 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 ?? 在本节中,这是确切的过程?我是否必须通过2个查询将数据插入到两个表(library,library_book_relation)中,例如1.插入到library ....和2.插入到library_book_relation ...。同时,或者还有其他方法可以完成这项工作?

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 插入新行后,您将获得在库表中插入的最后一个ID
  3. Insert your library books (relation) using your last id as a foreign key to library table 使用您的最后一个ID作为图书馆表的外键插入图书馆书(关系)

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 从library.lib_id = library_books_relation.lib_id上的库内部连接library_books_relation中选择*,其中lib_id = something

Or you can retrieve all the records by removing the 'where' clause. 或者,您可以通过删除“ where”子句来检索所有记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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