Relational modelling
Introducido
6:35
Bases de datos
A database is a set of true sentences about a domain. This course shows how to model, query, protect and govern data. The first three units model and shape it…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| relationship/rɪˈleɪʃənʃɪp/ | Relación |
| database/ˈdeɪtəbeɪs/ | An organised collection of data that can be accessed and managed. |
| entity/ˈentɪti/ | Entidad |
| cardinality/ˌkɑːdɪˈnælɪti/ | cardinalidad |
| primary key/ˈpraɪməri kiː/ | clave primaria |
| foreign key/ˈfɒrən kiː/ | clave foránea |
| referential integrity/ˌrefəˈrenʃl ɪnˈteɡrɪti/ | the rule that every foreign key value must match an existing primary key |
| many-to-many/ˈmeni tə ˈmeni/ | A database relationship in which each record on either side may be associated with several records on the other side. |
| junction table/ˈdʒʌŋkʃn ˈteɪbl/ | a table that links two entities in a many-to-many relationship |
| one-to-many/wʌn tə ˈmeni/ | A relationship in which one instance of an entity can be associated with several instances of another entity. |
| weak entity/wiːk ˈentɪti/ | an entity that cannot be identified without the entity it depends on |
| participation/pɑːˌtɪsɪˈpeɪʃn/ | whether every entity must take part in a relationship (total) or may not (partial) |
Entidades, relaciones, claves
- Un modelo de bases de datos es un conjunto de oraciones verdaderas sobre el dominio. Una entidad es una cosa que contamos (un Estudiante); una relación conecta entidades (se matricula). La cardinalidad en cada extremo —uno o muchos— se convierte en claves y tablas.
- Una clave primaria identifica una fila de forma única; una clave foránea la referencia, y el motor aplica la integridad referencial: ninguna matrícula puede nombrar un estudiante inexistente.


A many-to-many relationship becomes —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The junction table holds the foreign-key pairs; neither end can hold the other.
Muchos a muchos necesita una tabla
- Un estudiante se matricula en muchos cursos; un curso tiene muchos estudiantes: la relación se convierte en su propia tabla intermedia de pares de claves foráneas.
- Las reglas viven en las claves:
PRIMARY KEY (student_id, course_id, term)hace imposible una segunda matrícula idéntica — rechazada por el motor, no por la aplicación.
PRIMARY KEY (student, course, term) enforces —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The composite key rejects duplicate triples at the engine level.
A many-to-many relationship can be stored as one foreign key column on either table.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
One column holds one value per row, so it can store only one partner. Many-to-many needs a junction table of key pairs, such as Enrollment(student_id, course_id).
La ruta de unión
- ¿Qué estudiantes toman los cursos de un departamento? Estudiante se une a Matrícula sobre
student_id, se une a Curso sobrecourse_id, se une a Departamento sobredept_id— tres uniones, cada una siguiendo una clave foránea. - Los datos de muestra: 8 estudiantes, 6 cursos, 14 inscripciones — el camino de unión produce 14 filas antes del filtrado. Nunca almacene el nombre de un estudiante dentro de Inscripción: duplica y deriva.
IDs sustitutos sobre correos electrónicos como claves: los correos cambian, las claves sustitutas nunca lo hacen.
The join path Student-Enrollment-Course-Department yields — rows on the sample data
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
14 enrollments carry the path; each enrollment is one joined row.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Cardinality decides the tables
- Each entity becomes a table. A one-to-many 一对多 relationship becomes a foreign key on the many side:
Course.dept_idpoints to Department. - A one-to-one relationship becomes a foreign key with a
UNIQUEconstraint. A many-to-many 多对多 relationship becomes a junction table. - A weak entity 弱实体 has no key of its own: a Section is identified by
(course_id, section_no), borrowing its owner's key. So a model with $5$ entities, three one-to-many and two many-to-many relationships needs $5 + 2 = 7$ tables.
A model has 4 entities, 3 one-to-many relationships and 2 many-to-many relationships. How many tables does it need?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
One table per entity plus one junction table per many-to-many: 4 + 2 = 6.
Each department offers many courses. Where does the foreign key go?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The many side holds the key: each course names its one department.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Must it take part?
- Cardinality says how many; participation 参与 says whether. Every Course must belong to a Department (total participation), so
Course.dept_idisNOT NULL. A Student may have no advisor yet (partial participation), soStudent.advisor_idmay beNULL. - The diagram's double line, or "at least 1", becomes one keyword in the table. Getting it wrong either blocks valid data or lets orphan rows in.
Every course must belong to a department. The column Course.dept_id should be:
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Total participation: the foreign key may not be missing.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Worked example: deleting a student with enrolments
- Student 7 has 3 enrolments. With
ON DELETE RESTRICT(the default), the engine refuses to delete the student while those rows exist. - With
ON DELETE CASCADEit deletes the student and all $\mathbf{3}$ enrolments.SET NULLis impossible here, becausestudent_idis part of the primary key 主键. Choose the rule from the domain: grades are records, so most registries use restrict.
Student 7 has 3 enrollments; ON DELETE CASCADE. Rows removed in total (student plus enrollments)?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
The student row plus 3 enrollment rows.
ON DELETE SET NULL works on Enrollment.student_id.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
It is part of the primary key, which cannot be NULL.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
- Copying a name into the junction table. The Student table owns that fact; copies drift apart.
- The foreign key on the wrong side. One-to-many puts it on the many side:
Course.dept_id, not a list of courses in Department. - Skipping cardinality. It decides the tables: a many-to-many relationship always needs a junction table 连接表.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
- Entities are things you count; relationships connect them; cardinality becomes keys.
- A primary key identifies a row; a foreign key refers to one, and the engine enforces integrity.
- Store each fact once. Cardinality decides the tables:
| Relationship | Becomes |
|---|---|
| one-to-one | a foreign key with UNIQUE |
| one-to-many | a foreign key on the many side |
| many-to-many | a junction table 连接表 of key pairs |
¿Qué salió mal? Solo el equipo del sitio ve esta información.