E-R diagrams and normalisation · Diagramas E-R y normalización
| English | Español |
|---|---|
| entity-relationship diagram/ˈentɪti rɪˈleɪʃənʃɪp ˈdaɪəɡræm/ | diagrama entidad-relación |
| normalisation/ˌnɔːməlaɪˈzeɪʃn/ | normalización |
| entity/ˈentɪti/ | entidad |
| cardinality/ˌkɑːdɪˈnælɪti/ | cardinalidad |
| one-to-many/wʌn tə ˈmeni/ | uno a muchos |
| many-to-many/ˈmeni tə ˈmeni/ | muchos a muchos |
| link table/lɪŋk ˈteɪbl/ | tabla de enlace |
| normal forms/ˈnɔːml fɔːmz/ | formas normales |
| atomic/əˈtɒmɪk/ | atómica |
| transitive dependency/ˈtrænsɪtɪv dɪˈpendənsi/ | dependencia transitiva |
Forty rows to change one phone number
- A school keeps its enrolments in one spreadsheet. Every row is one student on one course, and every row also carries the student's form tutor and the tutor's phone number.
- The tutor changes her number. Forty rows have to be edited. Thirty-nine are. For the rest of the year, one course list rings a stranger.
- Nothing was mistyped. The fault was in the design: a fact that belongs to the tutor was stored once per enrolment, so it could be true in one place and false in another.
- This lesson is the two design tools that prevent that: the entity-relationship diagram 实体关系图, which draws the structure, and normalisation 规范化, which removes the repetition.
Cuarenta filas para cambiar un número de teléfono
- Una escuela mantiene sus matrículas en una hoja de cálculo. Cada fila representa a un estudiante en un curso, y cada fila también contiene el tutor del grupo y el número de teléfono del tutor.
- El tutor cambia su número. Cuarenta filas deben editarse. Treinta y nueve se corrigen. Para el resto del año, una lista de cursos llamará a un desconocido.
- No hubo ningún error tipográfico. El fallo estaba en el diseño: un hecho perteneciente al tutor se almacenaba una vez por matrícula, por lo que podía ser verdadero en un lugar y falso en otro.
- Esta lección trata sobre las dos herramientas de diseño que evitan esto: el diagrama de entidad-relación 实体关系图, que dibuja la estructura, y la normalización 规范化, que elimina la repetición.
Entity-relationship diagrams
- An entity-relationship diagram (E-R diagram) documents a database design: each entity 实体 is a rectangle, each relationship is a line between two rectangles, and the cardinality 基数 is marked at each end.
- In crow's-foot notation a single bar means "one" and a three-pronged foot means "many". Read each line in both directions: each customer places many orders; each order is placed by one customer.
- The diagram is drawn before any table is created, and the relationships on it become the foreign keys.
One rectangle per entity, one line per relationship
A bar for one, a foot for many
Diagramas de entidad-relación
- Un diagrama de entidad-relación (diagrama E-R) documenta el diseño de una base de datos: cada entidad 实体 es un rectángulo, cada relación es una línea entre dos rectángulos, y la cardinalidad 基数 se marca en cada extremo.
- En la notación "pie de cuervo" (crow's-foot), una barra simple significa "uno" y un pie de tres puntas significa "muchos". Lee cada línea en ambas direcciones: cada cliente realiza muchos pedidos; cada pedido es realizado por un solo cliente.
- El diagrama se dibuja antes de crear cualquier tabla, y las relaciones en él se convierten en claves foráneas.

Un rectángulo por entidad, una línea por relación

Una barra para uno, un pie para muchos
In an E-R diagram, the number of one entity that can relate to one of the other, marked at each end of the line, is the ____. · En un diagrama E-R, el número de una entidad que puede relacionarse con otra marcada en cada extremo de la línea es la ____.
Cardinality is one or many at each end; crow's-foot notation draws a bar for one and a foot for many. · La cardinalidad es uno o muchos en cada extremo; la notación de pie de cuervo dibuja una barra para uno y un pie para muchos.
The three kinds of relationship
- One-to-one (1:1): each member has one library card and each card belongs to one member. Rare; the two entities are often merged into one table.
- One-to-many 一对多 (1:M): one customer places many orders; each order belongs to one customer. Implemented by putting the "one" side's primary key into the "many" side's table as a foreign key.
- Many-to-many 多对多 (M:N): a student takes many courses and a course has many students. It cannot be implemented directly; it needs a link table.
Los tres tipos de relación
- Uno a uno (1:1): cada miembro tiene una tarjeta de biblioteca y cada tarjeta pertenece a un solo miembro. Raro; las dos entidades suelen fusionarse en una sola tabla.
- Uno a muchos 一对多 (1:M): un cliente realiza muchos pedidos; cada pedido pertenece a un solo cliente. Se implementa colocando la clave primaria del lado "uno" en la tabla del lado "muchos" como clave foránea.
- Muchos a muchos 多对多 (M:N): un estudiante cursa muchos cursos y un curso tiene muchos estudiantes. No se puede implementar directamente; necesita una tabla intermedia.
Each customer can place many orders, but each order belongs to one customer. This relationship is: · Cada cliente puede realizar muchos pedidos, pero cada pedido pertenece a un solo cliente. Esta relación es:
One customer → many orders, each order → one customer: a one-to-many relationship. · Un cliente → muchos pedidos, cada pedido → un cliente: una relación uno-a-muchos.
Match each relationship to its cardinality. · Empareja cada relación con su cardinalidad.
1:1 each side has one; 1:M one side has many; M:N both sides have many (needs a link table). · 1:1 cada lado tiene uno; 1:M un lado tiene muchos; M:N ambos lados tienen muchos (requiere una tabla intermedia).
Worked example: draw the E-R diagram
- A school has teachers, classes and students. Each teacher teaches many classes; each class is taught by one teacher. Each class has many students; each student is in one class. Students may join many clubs and each club has many students.
- Four rectangles:
TEACHER,CLASS,STUDENT,CLUB.TEACHER—CLASSis one-to-many, the foot atCLASS.CLASS—STUDENTis one-to-many, the foot atSTUDENT.STUDENT—CLUBis many-to-many, a foot at both ends. - The marks: every entity present, every relationship drawn, and the correct cardinality symbol at each end. A line with no symbols is half an answer.
Ejemplo resuelto: dibujar el diagrama E-R
- Una escuela tiene profesores, clases y estudiantes. Cada profesor imparte muchas clases; cada clase es impartida por un solo profesor. Cada clase tiene muchos estudiantes; cada estudiante está en una sola clase. Los estudiantes pueden unirse a muchos clubes y cada club tiene muchos estudiantes.
- Cuatro rectángulos:
TEACHER,CLASS,STUDENT,CLUB.TEACHER—CLASSes uno a muchos, el pie está enCLASS.CLASS—STUDENTes uno a muchos, el pie está enSTUDENT.STUDENT—CLUBes muchos a muchos, hay un pie en ambos extremos. - Las calificaciones: cada entidad presente, cada relación dibujada, y el símbolo de cardinalidad correcto en cada extremo. Una línea sin símbolos es media respuesta.
Link tables
- A many-to-many relationship is broken into two one-to-many relationships through a link table 连接表 that holds the two foreign keys.
ENROLMENT(StudentID, CourseID, EnrolmentDate): one student has many enrolments, one course has many enrolments, and each row is one student on one course. Its primary key is the composite of the two foreign keys.- Data about the pairing itself, the date, a grade, goes in the link table; data about the student or the course stays in its own table.
One many-to-many becomes two one-to-many
Tablas intermedias
- Una relación de muchos a muchos se divide en dos relaciones uno a muchos a través de una tabla intermedia 连接表 que contiene las dos claves foráneas.
ENROLMENT(StudentID, CourseID, EnrolmentDate): un estudiante tiene muchas matrículas, un curso tiene muchas matrículas, y cada fila representa a un estudiante en un curso. Su clave primaria es la compuesta de las dos claves foráneas.- Los datos sobre la propia combinación, la fecha, una nota, van en la tabla intermedia; los datos sobre el estudiante o el curso permanecen en su propia tabla.

Una relación muchos a muchos se convierte en dos relaciones uno a muchos
How is a many-to-many relationship implemented in a relational database? · ¿Cómo se implementa una relación muchos-a-muchos en una base de datos relacional?
A link (junction) table holds a foreign key to each side, turning M:N into two 1:M relationships. · Una tabla intermedia (link table) contiene una clave foránea a cada lado, convirtiendo M:N en dos relaciones 1:M.
ENROLMENT(StudentID, CourseID, EnrolmentDate) is a link table. Which statements are true? Select all · todos that apply. · MATRICULACIÓN(StudentID, CourseID, EnrolmentDate) es una tabla intermedia. ¿Cuáles afirmaciones son verdaderas? Selecciona todas las que correspondan.
The link table holds the pairing and facts about the pairing. The student's own data stays in STUDENT, or it would repeat on every enrolment. · La tabla intermedia contiene el emparejamiento y los hechos sobre él. Los datos propios del estudiante permanecen en STUDENT, de lo contrario se repetirían en cada matriculación.
Normalisation
- Normalisation organises the tables so that each fact is stored exactly once, cutting redundancy and inconsistency. It passes through the normal forms 范式 in order: first, second, third.
- The procedure: find the entities and their attributes; choose a primary key for each; remove repeating groups and non-atomic values (1NF); remove attributes that depend on only part of a composite key (2NF); remove attributes that depend on another non-key attribute (3NF); add foreign keys for the relationships.
- The cost is more tables and more joins. The exam asks for 3NF.
Normalización
- La normalización organiza las tablas para que cada dato se almacene exactamente una vez, reduciendo la redundancia y la inconsistencia. Pasa por las formas normales 范式 en orden: primera, segunda, tercera.
- El procedimiento: encontrar las entidades y sus atributos; elegir una clave primaria para cada una; eliminar grupos repetitivos y valores no atómicos (1NF); eliminar atributos que dependen solo de parte de una clave compuesta (2NF); eliminar atributos que dependen de otro atributo no clave (3NF); añadir claves foráneas para las relaciones.
- El coste son más tablas y más uniones (joins). El examen pide 3NF.
Database service lab · Laboratorio de servicio de base de datos
Watch how a DBMS turns a query into safe shared data access. · Observa cómo un SGBD transforma una consulta en acceso seguro a datos compartidos.
Put the normal forms in the order you apply them. · Coloca las formas normales en el orden en que se aplican.
You reach 3NF by passing through 1NF then 2NF — each builds on the previous. · Alcanzas la 3FN pasando por la 1FN y luego la 2FN; cada una se basa en la anterior.
The main aim of normalisation is to: · El objetivo principal de la normalización es:
Normalising to 3NF stores each fact once, removing update/insert/delete anomalies (at the cost of more joins). · Normalizar hasta la 3FN almacena cada hecho una sola vez, eliminando anomalías de actualización/inserción/borrado (a costa de más joins).
First normal form
- A table is in 1NF when every field holds a single, atomic 原子 value, there are no repeating groups, and there is a primary key.
STUDENT(StudentID, Name, Phone)withPhoneholding0123, 0456is not atomic.STUDENT(StudentID, Name, Course1, Course2, Course3)has a repeating group.- Fix both by moving the repeated data to its own table with a row per value:
STUDENT_PHONE(StudentID, Phone),ENROLMENT(StudentID, CourseID).
Primera forma normal
- Una tabla está en 1NF cuando cada campo contiene un único valor atómico 原子, no hay grupos repetitivos y existe una clave primaria.
STUDENT(StudentID, Name, Phone)conPhoneconteniendo0123, 0456no es atómico.STUDENT(StudentID, Name, Course1, Course2, Course3)tiene un grupo repetitivo.- Corregir ambos moviendo los datos repetidos a su propia tabla con una fila por valor:
STUDENT_PHONE(StudentID, Phone),ENROLMENT(StudentID, CourseID).
A Phone field holds "0123, 0456" for one student. Which normal form does the table fail? · Un campo Teléfono contiene "0123, 0456" para un estudiante. ¿A qué forma normal falla la tabla?
Two values in one cell is the 1NF failure. Move the numbers to STUDENT_PHONE(StudentID, Phone), one per row. · Dos valores en una celda es el fallo de la 1FN. Mueve los números a STUDENT_PHONE(StudentID, Phone), uno por fila.
Worked example: second normal form
ORDER(OrderID, CustomerID, CustomerName, ProductID, Quantity)has the composite primary key(OrderID, ProductID). Is it in 2NF?- Test each non-key field against the whole key.
Quantitydepends on bothOrderIDandProductID: which order, which product. Fine. CustomerIDandCustomerNamedepend onOrderIDalone, only part of the key: a partial dependency, so the table is not in 2NF. Split it:ORDER(OrderID, CustomerID, CustomerName)andORDER_LINE(OrderID, ProductID, Quantity).
Ejemplo resuelto: segunda forma normal
ORDER(OrderID, CustomerID, CustomerName, ProductID, Quantity)tiene la clave primaria compuesta(OrderID, ProductID). ¿Está en 2NF?- Prueba cada campo no clave contra la clave entera.
Quantitydepende tanto deOrderIDcomo deProductID: qué pedido, qué producto. Correcto. CustomerIDyCustomerNamedependen solo deOrderID, es decir, solo de una parte de la clave: una dependencia parcial, por lo que la tabla no está en 2NF. Divídela:ORDER(OrderID, CustomerID, CustomerName)yORDER_LINE(OrderID, ProductID, Quantity).
Worked example: third normal form
- Is
ORDER(OrderID, CustomerID, CustomerName)in 3NF? - A table is in 3NF when it is in 2NF and every non-key field depends only on the primary key, not on another non-key field.
CustomerNamedepends onCustomerID, which is not the key: a transitive dependency 传递依赖, so the table is not in 3NF. - Split again:
ORDER(OrderID, CustomerID)andCUSTOMER(CustomerID, CustomerName), withCustomerIDa foreign key. The name is now stored once, however many orders the customer places.
Each form removes one kind of dependency
Ejemplo resuelto: tercera forma normal
- ¿Está
ORDER(OrderID, CustomerID, CustomerName)en 3NF? - Una tabla está en 3NF cuando está en 2NF y cada campo no clave depende únicamente de la clave primaria, no de otro campo no clave.
CustomerNamedepende deCustomerID, que no es la clave: una dependencia transitiva 传递依赖, por lo que la tabla no está en 3NF. - Vuelve a dividirla:
ORDER(OrderID, CustomerID)yCUSTOMER(CustomerID, CustomerName), conCustomerIDcomo clave foránea. Ahora el nombre se almacena una sola vez, independientemente de cuántos pedidos realice el cliente.

Cada forma elimina un tipo de dependencia
Normalising to 3NF stores each fact once and removes update anomalies, at the cost of more tables and joins. · Normalizar a la 3FN almacena cada hecho una sola vez y elimina anomalías de actualización, a costa de tener más tablas y joins.
That trade-off — cleaner data versus more joins — is why 3NF is the usual target. · Ese compromiso — datos más limpios frente a más joins — es por qué la 3NF es el objetivo habitual.
Saying why a table is, or is not, in 3NF
- Not in 3NF: name the dependency. "
TEACHERis not in 3NF because the non-key attributeDepartmentNamedepends on the non-key attributeDepartmentID, not on the primary key." - In 3NF: cover all three conditions. "Every attribute is atomic with no repeating groups; there is no partial dependency on part of the key; every non-key attribute depends only on the primary key, with no transitive dependency."
- Then, if asked, give the normalised tables in the standard notation with the foreign keys marked.
Explicar por qué una tabla está, o no está, en 3NF
- No está en 3NF: nombra la dependencia. "
TEACHERno está en 3NF porque el atributo no claveDepartmentNamedepende del atributo no claveDepartmentID, no de la clave primaria." - Está en 3NF: cubre las tres condiciones. "Cada atributo es atómico sin grupos repetitivos; no hay dependencia parcial sobre una parte de la clave; cada atributo no clave depende únicamente de la clave primaria, sin dependencias transitivas."
- Luego, si se pregunta, proporciona las tablas normalizadas en la notación estándar con las claves foráneas marcadas.
In TEACHER(TeacherID, Name, DepartmentID, DepartmentName), why is the table not in 3NF? · En PROFESOR(TeacherID, Name, DepartmentID, DepartmentName), ¿por qué la tabla no está en 3FN?
A transitive dependency. Split out DEPARTMENT(DepartmentID, DepartmentName) and keep DepartmentID in TEACHER as a foreign key. · Dependencia transitiva. Extrae DEPARTAMENTO(DepartmentID, DepartmentName) y mantiene DepartmentID en PROFESOR como clave foránea.
Marks that slip away
- 2NF is only a question when the primary key is composite. A single-field key cannot have a partial dependency.
- 3NF requires 2NF. Say both when justifying.
- Atomic means one value per cell. "Two phone numbers in one field" is a 1NF failure, not a 3NF one.
- Naming the normal form is not the answer; naming the dependency is. More tables after normalising is the point, not a fault.
Puntos que se pierden
- La 2NF solo es una cuestión cuando la clave primaria es compuesta. Una clave de un solo campo no puede tener una dependencia parcial.
- La 3NF requiere 2NF. Menciona ambas al justificar.
- Atómico significa un valor por celda. "Dos números de teléfono en un campo" es un fallo de 1NF, no de 3NF.
- Nombrar la forma normal no es la respuesta; nombrar la dependencia sí lo es. Tener más tablas después de normalizar es el objetivo, no un error.
You've got it
- an E-R diagram shows entities as rectangles and relationships as lines with the cardinality at each end: 1:1, 1:M, M:N
- a many-to-many relationship is stored through a link table of the two foreign keys, its primary key their composite
- 1NF atomic values, no repeating groups, a primary key · 2NF no partial dependency on part of a composite key · 3NF no transitive dependency between non-key attributes
- justify by naming the dependency, then give the split tables with their foreign keys
Lo has entendido
- un diagrama E-R muestra las entidades como rectángulos y las relaciones como líneas con la cardinalidad en cada extremo: 1:1, 1:M, M:N
- una relación de muchos a muchos se almacena mediante una tabla intermedia de las dos claves foráneas, siendo su clave primaria la compuesta de estas
- 1NF valores atómicos, sin grupos repetitivos, una clave primaria · 2NF sin dependencia parcial sobre una parte de una clave compuesta · 3NF sin dependencia transitiva entre atributos no clave
- justifica nombrando la dependencia, luego proporciona las tablas divididas con sus claves foráneas