Database design in-one, many-to-many relationship based on foreign key condition to achieve and methods

Author: Two crooked knowledge iSk2y
link: https: //www.jianshu.com/p/2b27c7ba0653
Source: Jane books

In the following table, for example departments and staff_info (add foreign key is pointing departments staff_info)

A field of the table as a foreign key conditions:

Column values must be non-null and the only 

test examples are as follows:
mysql> create table departments (dep_id int(4),dep_name varchar(11));
Query OK, 0 rows affected (0.02 sec)

mysql> desc departments;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| dep_id   | int(4)      | YES  |     | NULL    |       |
| dep_name | varchar(11) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
rows in  the SET ( 0.00 sec) 

# create a foreign key is not successful 
MySQL > the Create the Table staff_info (s_id int , name VARCHAR ( 20 ), dep_id int , Foreign Key (dep_id) the References the Departments (dep_id)); 
ERROR 1215 (HY000): of Can not the Add key foreign 

# dep_id non-empty set, still can not successfully create a foreign key 
MySQL > the ALTER dep_id the Modify the Table the Departments int ( 4 ) not null ; 
Query the OK, 0 rows affected ( 0.02 sec) 
Records: 0   Duplicates: 0   Warnings: 0 

MySQL> desc departments;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| dep_id   | int(4)      | NO   |     | NULL    |       |
| dep_name | varchar(11) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> create table staff_info (s_id int,name varchar(20),dep_id int, Foreign Key (the dep_id) References Departments (the dep_id)); 
ERROR 1215 (HY000): Can Not the Add Foreign Key constraint 

# when set field is unique only field, set this field to the foreign key success 
MySQL > ALTER Table Departments Modify the dep_id int ( . 4 ) UNIQUE; 
Query the OK, 0 rows affected ( 0.01 sec) 
Records: 0   Duplicates: 0   Warnings: 0 

MySQL > desc Departments;                                                               
+ + ---------- ---------- + ------ + ----- + --- --------- + ------- + | Field, | Type | Null | Key | the Default | Extra | + ---------- + --- + ------ + ----- + ---------- --------- + ------- + | dep_id | int(4) | YES | UNI | NULL | | | dep_name | varchar(11) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ rows in set (0.01 sec) mysql> create table staff_info (s_id int,name varchar(20),dep_id int,foreign key(dep_id) references departments(dep_id)); Query OK, 0 rows affected (0.02 sec)

Special attention: the main outer joint requires two tables must be using the same engine type a: two tables are innodb storage engine must

 

 

Method of adding a foreign key

 

There are two general methods to add when creating the table, add or late

 

Creating added time

mysql> create table score(
    -> sid int not null auto_increment primary key,
    -> student_id int,
    -> corse_id int,
    -> number int not null,
    -> constraint fk_sid foreign key (student_id) references student(sid),
    -> constraint fk_corse_id foreign key (corse_id) references course(cid));
 
-----------------------------------------------------------------------------------
[CONSTRAINT symbol] FOREIGN KEY [id] (从表的字段1)

REFERENCES tbl_name (主表的字段2)

[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]

[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION} 

CONSTRAINT symbol: and shalt call the name of a foreign key constraint, we have a name, later to find it very convenient. If you do not add this parameter, the system will automatically assign a name.

FOREIGN KEY: from a field in a table as a foreign key field.

REFERENCES: is mapped to the fields in the primary table 2.

The latter four parameters ON DELETE: delete when represents a record in the primary table, the agreement made.

After creating added

ALTER TABLE employee ADD FOREIGN KEY(dept_id) REFERENCES department(id); 

ALTER TABLE employee: In the operating table employee;

ADD FOREIGN KEY (dept_id): dept_id table from the field to add a foreign key;

REFERENCES department (id): mapped to the primary table to which department the field id.

Remove the foreign key

When delete a foreign key if you do not know the name of the foreign key foreign key name on the first acquisition

show create table emp \G;

Remove the foreign key

alter table emp drop foreign key foreign key name; 

 

The following is the key

Realization relationship

In the entity-relationship model, we know that there are three relationships: one to one, one to many, many to many. This is only a conceptual relationship, but in a real relational database, we have only foreign keys , and there is no relationship between these three, then we'll talk about in a relational database management system, how to achieve these three relationships.

Many

Here to explain many, because this relationship is the simplest. And many-to-many is one thing, so I will not mention many-word. Is a concept many object A will correspond to a plurality of objects B, viewed from angle B, only one object for an object A. B For example, classes and students is one to many relationship. A corresponding number of students in class, a student will only be for a class.

The reason for that is simple-to-many relationship, because the RDBMS [foreign keys] in fact represent many relationship. For many relationship, we just need to build on the "many" table in the "one" foreign key can be, and "one" side of the table do not need to make any changes. For example, students in the class relations said before. Class table unchanged, increase student table as a foreign key Id class.

Many to many

Many relationship in database design than the one to be common, so let us talk about here-many. Is a many-to object A corresponding to the plurality of object B, from the point B to see, a plurality of objects corresponding to the object B will A. For example, the relationship between students and the course is many relationship. A student learning many courses, one elective course to have more than one student.

In an RDBMS, you must use an intermediate table to represent many to many relationship. Middle of the table we can be divided into two, one is purely middle of the table represents the relationship between a middle of the table is a middle entity.

Pure intermediate table showing the relationship is simple, requires only two: AID and BID, associated keys to the primary key of the table other than the AID of the A, B key associated with the primary key table than BID, and then the two-column primary key. This intermediate is a purely many relationship table exists, there will be a corresponding service in the corresponding entity. For example, the relationship between students and courses mentioned earlier, if we only what lesson on what students need to know, what lessons which students choose, do not need to have more information about the case, we can establish a "Student Program" middle of the table , which is only two student ID and course ID field.

Intermediate entity is based purely on the intermediate table, together with additional properties, to form a new entity. For example, the relationship between students and courses mentioned earlier, if we need to record time student enrollment, students choose this course after the examination results, then we like to establish a "enrollment" entity that has the following attributes:

 

This is an intermediate entity, it has been completely out of the ordinary-many relationship middle of the table, but instead in the form of an entity, so in accordance with the principles mentioned in the previous blog a primary key design, we can establish a separate elective ID column as the primary key of the database, the primary key itself is not business meaning.

One to One

The concept is to say one object A corresponds to a maximum of one object B, from the point B to see, is a maximum of one object corresponds to the object A. B For example, the relationship between teacher (teacher) and class, a teacher manage up to a class, a class also most one class.

One relationship in the database design, is the least used of the relationship, because in general, if two entities are to-many relationship, then we can merge these two entities into a single entity. But in the design, we will still face two completely different entities, there is a one to one relationship between.

RDBMS is implemented in one of a table on which the foreign key to another table established, while establishing a unique constraint on the foreign key column. For example, he said before the class teacher and class relations, we can create a class field in the class table, and then create a unique constraint in this field. Because each class will have a teacher, so the teacher does not allow field is empty. A teacher can be a teacher of a class can also be improper and any homeroom teacher, but can not appear twice on the field the class teacher's table, so it is up to a class when the class teacher, so the design to meet the demand.

So can we, in turn, managed to establish in the class teacher table Id field, point to the class table, and the establishment of a unique constraint it? In addition to dissatisfaction "Each class must have a class" out of this business constraints, the other no problem. So if one of the case, if there must be required to hold the other side, the increased foreign key fields in which way; if this is not a must hold another type of entity, then it is which side to add foreign key columns Row.


/ * * Student table * / 
the CREATE TABLE Student ( 
stu_id INT AUTO_INCREMENT, 
NAME VARCHAR ( 30 ), 
Age INT, 
class VARCHAR ( 50 ), 
address VARCHAR ( 100 ), 
PRIMARY KEY (stu_id) 
) 
 
/ * student schedule * / 
the CREATE tABLE course, ( 
cour_id INT AUTO_INCREMENT, 
NAME VARCHAR ( 50 ), 
CODE VARCHAR ( 30 ), 
PRIMARY KEY (cour_id) 
) 
 
/ * * student program association table * / 
the CREATE tABLE Stu_Cour ( 
sc_id INT AUTO_INCREMENT, 
stu_id INT,  
cour_id INT,
PRIMARY KEY (sc_id)
)

/*添加外键约束*/
ALTER TABLE Stu_Cour ADD CONSTRAINT stu_FK1 FOREIGN KEY(stu_id) REFERENCES student(stu_id)
ALTER TABLE Stu_Cour ADD CONSTRAINT cour_FK2 FOREIGN KEY(cour_id) REFERENCES Course(cour_id)

 



Guess you like

Origin www.cnblogs.com/isme-zjh/p/11793046.html