MySQL's multi-table design and associative query (database design paradigm, use of foreign keys, cross between inside and outside of associated query)

Multi-table design-associative query

Why do you need a multi-table design?

The purpose of multi-table design is to eliminate redundant data, split a table into multiple tables, or extract common data from multiple tables into one table.

For example, there are the following two tables

Numbering Name Nation Country of Citizenship
1 Zhang San Han nationality China
2 Li Si Han nationality China
Numbering province Country of Citizenship
1 Shaanxi China
2 Guangzhou China

There are a lot of redundancy in these two tables, such as ethnicity and nationality. If we design them with multiple tables, it can become

National table

Ethnic number Nation
1 Han nationality
2 Hui

Country table

Country code Country of Citizenship
1 China
2 Pakistan

And the top two tables can become

Numbering Name Ethnic number Country code
1 Zhang San 1 1
2 Li Si 1 1
Numbering province Country code
1 Xi'an 1
1 Guangzhou 1

In this way, we can eliminate duplicate redundant data, and can reuse one data.

Database design paradigm

1. In order to build a database with less redundancy and a reasonable structure, certain rules must be followed when designing the database. This rule is also called the temporal paradigm in relational databases. The paradigm is a summary that meets a certain design requirement.

2. There are 6 paradigms in current relational databases:

(1) First Normal Form (1NF);

(2) Second Normal Form (2NF);

(3) Third Normal Form (3NF);

(4) Bath-Cord Paradigm (BCNF);

(5) Fourth Normal Form (4NF);

(6) Fifth normal form (5NF), also known as perfect normal form.

3. The paradigm that meets the minimum requirements is the first paradigm (1NF). On the basis of the first paradigm, further satisfying more specification requirements is called the second paradigm (2NF), and the rest of the paradigm is in turn. Generally speaking, the database Only the third normal form (3NF) is needed.

First Normal Form (1NF)

The first normal form is the most basic normal form. It is necessary to ensure that each column in the database table remains atomic. If all field values ​​in the database table are indecomposable atomic values, it means that the database table meets the first normal form.

for example

Numbering Name contact details
1 Wang Mazi Email/Phone/qq

Table structure after satisfying the first normal form

Numbering Name mailbox phone QQ
1 Wang Mazi [email protected] 1313131 2212321

Second Normal Form (2NF)

1. The second paradigm is to have a primary key, requiring other fields to depend on the primary key;

2. Without a primary key, there is no uniqueness, and without uniqueness, this row of records cannot be located in the collection, so the primary key is required.

3. Why do other fields depend on the primary key? Because they do not depend on the primary key, they cannot be found. More importantly, the row of records composed of other fields and the primary key express the same thing, and the primary key is unique, they It only needs to rely on the primary key and it becomes unique.

Third Normal Form (3NF)

The third paradigm is to eliminate transitive dependence and facilitate understanding. It can be regarded as "eliminating redundancy".

Order number Quantity Product Number product name unit price order amount
1000 2 2020 Cell phone 2000 4000
Product Number product name unit price
2020 Cell phone 2000
Order number Quantity order amount Product Number
1000 2 4000 2020

Generally speaking, the database only needs third normal form (3NF).

Database instance

Student table: name, gender, mobile phone number, grade number, registration time
Grade table: grade number, grade name, grade introduction
Course schedule: course number, course name, course introduction
Several relationships between tables and tables:
1.One One-to-one association;
2. One-to-many association;
3. Many-to-one association;
4. Many-to-many association.

-- 创建年级表
CREATE TABLE t_grade(
	g_id INT PRIMARY KEY AUTO_INCREMENT COMMENT'年级编号',
	g_name VARCHAR(10) COMMENT'年级名称',
	g_desc VARCHAR(50) COMMENT'年级介绍'
)

Insert picture description here

-- 创建学生表
CREATE TABLE t_stu(
	s_id INT PRIMARY KEY AUTO_INCREMENT COMMENT'学号',
	s_name VARCHAR(10) COMMENT'姓名',
	s_sex CHAR(1) DEFAULT'男' COMMENT'性别',
	s_phone INT(11) COMMENT'电话',
	s_g_id INT COMMENT'年级编号',
	reg_time DATETIME COMMENT'注册时间'
)

Insert picture description here

Introduce the weak association relationship: The table structure is essentially unrelated. The relationship between the table and the table is artificially defined. Deleting the data in the association table has no effect on the other. The grade number and the grade table in the above figure are a kind of weak association. relationship.

Foreign key

Let's talk about the strong association relationship, add constraints to the foreign key, and force the foreign key to have an association relationship with the corresponding primary key (foreign keys, corresponding to the primary key in another table)

1. Foreign key: refer to a record of another data table.

2. The data type of the foreign key column should be consistent with the primary key column.

3.The association/reference relationship between the data tables is established by the specific primary key and foreign key.

The syntax for adding foreign keys when creating a table:

create table 表名(
	constraint 约束名 foreign key(外键列) references 主键表(主键列)
)

Add foreign key constraint syntax:

alter table 表名 
add [constraint 约束名(自己起的)] 
foreign key(外键列) 
references 关联表(主键)

Delete foreign key syntax:

alter table 表名 drop foreign key 外键约束名;

Database instance

Add a foreign key to the above table

ALTER TABLE t_stu 
ADD CONSTRAINT s_foreign_key 
FOREIGN KEY(s_g_id) 
REFERENCES t_grade(g_id); 
-- 创建课程表,多对多关系,一个学生对应多个课程,一个课程对应多个学生
CREATE TABLE t_course(
	c_id INT PRIMARY KEY AUTO_INCREMENT COMMENT'课程号',
	c_name VARCHAR(10) COMMENT'课程名',
	c_desc VARCHAR(20) COMMENT'课程介绍'
)
-- 设计关系表来存储多个数据之间的关系
CREATE TABLE t_stu_course(
	sc_id INT PRIMARY KEY AUTO_INCREMENT,
	sc_stu_id INT,
	sc_course_id INT,
	CONSTRAINT stu_id_fk FOREIGN KEY(sc_stu_id) REFERENCES t_stu(s_id),
	CONSTRAINT cou_id_fk FOREIGN KEY(sc_course_id) REFERENCES t_course(c_id)
)

Insert picture description here
Insert picture description here

note

1. When there is no corresponding record in the master table, the record cannot be added to the slave table

2. Cannot change the value in the main table and cause the records in the slave table to be isolated

3. There is a record corresponding to the main table from the table, and the row cannot be deleted from the main table

4. Before deleting the primary table, delete the secondary table

Related query

Overview

1. Associated query is also called multi-table query. When the query field comes from multiple tables, join query will be used

2. Cartesian product phenomenon: Table 1 has m rows, Table 2 has n rows, and the query result has m*n rows

(1) Reason: There is no valid connection condition

(2) How to avoid: Add valid connection conditions

classification

Inner join

Query the intersection data in the two tables that meet the conditions

grammar:

select 结果 from1,2 where1.1=2.2
SELECT s_id,s_name,s_sex,s_g_id,g_name,g_id 
FROM t_stu,t_grade
WHERE s_g_id = g_id

Insert picture description here

1. Equivalent connection

#等值连接
/*
语法
select 结果 from 表名 inner join 被连接的表名(外键表) on 外键=主键
*/
SELECT * 
FROM t_stu
INNER JOIN t_grade ON s_g_id = g_id 

Insert picture description here

2. Non-equivalent connection

#创建一个等级表
CREATE TABLE t_level(
	l_name CHAR(1),
	l_min_score INT,
	l_max_score INT
)
/*
非等值连接
语法
select 结果
from 表1
inner join 表2
on 表1.列1 between 表2.列2 and 表2.列3
*/
SELECT
  s_name,
  l_name
FROM
  t_stu
  INNER JOIN t_level
    ON s_score BETWEEN l_min_score
    AND l_max_score

Insert picture description here

Insert picture description here

3. Self-connection: Establish a connection relationship in a table

CREATE TABLE t_area(
	a_id INT,
	a_name VARCHAR(10),
	a_father INT
)
#在一张表中建立连接关系
SELECT
  t1.a_name,
  t2.a_name
FROM
  t_area t1
  INNER JOIN t_area t2
    ON t1.a_father = t2.a_id;

Insert picture description here
Insert picture description here

Outer join

1. Left outer join (left join)

/*
语法
select 结果
from 表1
left join 表2 
on 表1.字段=表2.字段l;

不管表1的字段与表2的字段是否有连接,都会显示表1的所有信息
*/
SELECT *
FROM t_stu s
LEFT JOIN t_grade g
ON s.s_g_id = g.g_id;

2. Right outer join (right join)

/*
语法
select 结果
from 表1
right join 表2 
on 表1.字段1=表2.字段2;

不管表1有没有和表2中的所有数据关联,都会显示出表2的所有
*/
SELECT *
FROM t_stu s
RIGHT JOIN t_grade g
ON s.s_g_id = g.g_id;
Cross connect
-- 交叉连接 类似于内连接
SELECT *
FROM t_stu s
CROSS JOIN t_grade g
ON s.s_g_id = g.g_id;

Guess you like

Origin blog.csdn.net/Lotus_dong/article/details/112913839