Appearance
Relational Model
As we know, relational databases are based on the relational model. Essentially, the relational model consists of several two-dimensional tables for storing data, which can be thought of as many Excel spreadsheets.
Each row in a table is called a record, which represents a logical piece of data.
Each column in a table is called a field. All records in the same table share the same fields.
Fields define the data type (such as integer, floating point, string, date, etc.) and whether NULL values are allowed. Note that NULL signifies the absence of data in a field. A NULL integer does not imply a value of 0, and a NULL string does not mean an empty string ''.
Tip
Generally, fields should avoid allowing NULL values. Disallowing NULL simplifies query conditions, speeds up queries, and helps applications read data without needing to check for NULL.
Unlike Excel tables, tables in a relational database need to establish relationships such as "one-to-many," "many-to-one," and "one-to-one" in order to organize and store data according to application logic.
For example, consider a class table:
ID | Name | Teacher |
---|---|---|
201 | Class 1 | Teacher Wang |
202 | Class 2 | Teacher Li |
Each row corresponds to a class, and one class corresponds to multiple students, so the relationship between the class table and the student table is "one-to-many":
ID | Name | Class ID | Gender | Age |
---|---|---|---|---|
1 | Xiao Ming | 201 | M | 9 |
2 | Xiao Hong | 202 | F | 8 |
3 | Xiao Jun | 202 | M | 8 |
4 | Xiao Bai | 201 | F | 9 |
Conversely, if we locate a record in the student table, for example, ID=1 for Xiao Ming, we can determine his class by finding the record in the class table with the corresponding Class ID of 201, which is Class 1. Thus, the relationship between the student table and the class table is "many-to-one."
If we break the class table down further and create a separate teacher table:
ID | Name | Age |
---|---|---|
A1 | Teacher Wang | 26 |
A2 | Teacher Zhang | 39 |
A3 | Teacher Li | 32 |
A4 | Teacher Zhao | 27 |
The class table would only store the Teacher ID:
ID | Name | Teacher ID |
---|---|---|
201 | Class 1 | A1 |
202 | Class 2 | A3 |
In this way, each class is associated with a specific teacher, creating a "one-to-one" relationship between the class table and the teacher table.
In relational databases, relationships are maintained through primary keys and foreign keys, which we will discuss in detail later.