text sql SQL多对多的例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text sql SQL多对多的例子相关的知识,希望对你有一定的参考价值。

#Students to student_classes is a 'many to many' relationship
  # many to many is 'one to many' in both directions
 
# Requires PKs from each of the other tables

# Usually requires three tables  1 -> junction -> 2


students:
id | first  | last
=====================
1  | John   | Lee
2  | Jane   | Wilson
3  | Daniel | Gomez
 
classes:
id | name    | teacher_id
==========================
1  | Biology | 2
2  | Physics | 4
3  | English | 77
 
enrollments
s_id | c_id
======================
  1  |  2   # John is taking Physics 
  1  |  3   # John is taking English
  2  |  2   # Jane is taking Physics
  3  |  1   # Daniel is taking Biology
  
  
  
   -- Getting all students for a class:

    SELECT s.student_id, last_name
      FROM enrollments 
INNER JOIN students s ON s.student_id = enrollments.student_id
     WHERE enrollments.class_id = X

 -- Getting all classes for a student: 

    SELECT c.class_id, name
      FROM enrollments 
INNER JOIN classes c ON c.class_id = enrollments.class_id
     WHERE enrollments.student_id = Y
     
     

以上是关于text sql SQL多对多的例子的主要内容,如果未能解决你的问题,请参考以下文章

sql 一对多的查询

MySQL选择多对多的位置

JPA 多对多JPQL查询语句怎么写?

关于一对多,多对多的多表查询的控制

“.”处或附近的QueryDSL语法错误在多对多的关系

关于多对多关系表做一个级联更新的问题(MYSQL),求高手解答SQL语句