Many-to-many relationships in databases and their implementation

Source: Internet
Author: User

A record in thing a can correspond to more than one record in thing B, and a record in thing B can correspond to multiple records in thing A. For example: In a school, a class can have more than one classroom teacher, and a teacher can teach multiple classes. At this point, you can introduce a table C to simulate many-to-many relationships.

SQL statements:

--Class TableCreate TableBanji (banji_idint Primary Key, Banji_numint  not NULL, Banji_namenvarchar( -))--TeachersCreate TableJiaoshi (jiaoshi_idint Primary Key, Jiaoshi_namenvarchar( $))--The third table is used to simulate the relationship between class and teacher.Create Tablebanji_jiaoshi_mapping (banji_idint constraintfk_banji_idForeign Key ReferencesBanji (banji_id), jiaoshi_idint Foreign Key ReferencesJiaoshi (jiaoshi_id), Kechengnvarchar( -),    constraintpk_banji_id_jiaoshi_idPrimary Key(Banji_id,jiaoshi_id,kecheng))--Delete a tableDrop TableBanji_jiaoshi_mapping

Database diagram:

Note: This article refers to the Hao bin of the teacher's SQL tutorial, but also added some of their own understanding of SQL, there is a wrong place to write the hope that we can point out.

Many-to-many relationships in databases and their implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.