简体   繁体   English

中级 SQL 表:有什么用?

[英]Intermediate SQL Table : What for?

I'm managing to create my first complicated J2E Solution and in every tutorial I find some sort of intermediary tables usage, like here :我正在设法创建我的第一个复杂的 J2E 解决方案,并且在每个教程中我都找到了某种中间表的用法,如下所示:

Tables : User, User_Roles, Roles While logic would simply add a key to user Table referring to it's role on Roles table, why the usage of that intermediary table ?表:User、User_Roles、Roles 虽然逻辑会简单地向 user 表添加一个键,指的是它在 Roles 表上的角色,但为什么要使用该中间表?

I thought it's one or two developpers choice, but everywhere I look for a tutorial, I find this sort of sql schema.我认为这是一两个开发人员的选择,但是在我寻找教程的任何地方,我都会找到这种 sql 模式。

Is it better ?这个会比较好吗 ? Does it help in something particular ?它对某些特定的事情有帮助吗? Speed, security ?速度,安全? Cause from a logic point of view, using one table User and a foreign key to Roles is better.因为从逻辑的角度来看,使用一个表 User 和一个 Roles 的外键更好。

Thank you谢谢

This is a common database relationship modeling called MN (Many To Many).这是一种常见的数据库关系建模,称为MN(Many To Many)。 A User can have many Roles, and a Role can be assigned to many Users, so you need the intermediary table.一个User可以有很多Role,一个Role可以分配给很多User,所以需要中间表。 Here's another example: a Teacher can teach many Classes, and each Class can be taught by many teachers (during different semesters, for example).再举一个例子:一个老师可以教很多班,每个班可以有很多老师教(例如,在不同的学期)。 In this case you need a Teacher-Class intermediary table.在这种情况下,您需要一个教师级中介表。

A different kind of relationship is 1-N (one to N).另一种关系是 1-N(一对 N)。 A User can have many Telephones, but each Telephone is owned by a single User.一个用户可以拥有多个电话,但每个电话由一个用户拥有。 In this case, a User's primary key (PK) is exported as a foreign key (FK) into the Telephones table.在这种情况下,用户的主键 (PK) 作为外键 (FK) 导出到电话表中。 No need for an intermediary table.不需要中间表。

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

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