当前位置:网站首页>Tutorial on the principle and application of database system (011) -- relational database
Tutorial on the principle and application of database system (011) -- relational database
2022-07-07 12:15:00 【Rsda DBA_ WGX】
Database system principle and Application Tutorial (011)—— relational database
Relational database management system is the most widely used database management system . such as :Oracle、MySQL、DB2、SQL Server etc. .
One 、 Relational data structure
1、 The mathematical definition of relationship
(1) Domain
A field is a set of values with the same data type . such as :{ male , Woman }、{ party member , League members , The crowd }、{ School of Management , Business School , Law school, , Academy of art }、 Student numbers of all students, etc .
(2) The cartesian product
Given a set of domains D1,D2,…,Dn, Then domain D1,D2,…,Dn The Cartesian product of is :
D1×D2×…×Dn={(d1,d2,…,dn) | di ∈ Di,i=1,2,…,n}
Each of these elements (d1,d2,…,dn) Is called a n Tuples , It's called tuple , Every value in a tuple di It is called a component .
Di The number of elements contained is called Di Base number of , If Di Based on mi(i=1,2,…,n), be D1×D2×…×Dn Based on :
Cartesian product can be represented by a two-dimensional table . A row in the table corresponds to a tuple , A column in the table corresponds to a field . For example, there are three domains :
D1 = full name = { Wang Ping , Li Li , Zhang Xiaogang }
D2 = Gender = { male , Woman }
D3 = Age = {19,20}
be D1、D2、D3 The Cartesian product of is :
D1×D2×D3 = {( Wang Ping , male ,19),( Wang Ping , male ,20),( Wang Ping , Woman ,19),( Wang Ping , Woman ,20),( Li Li , male ,19),( Li Li , male ,20),( Li Li , Woman ,19),( Li Li , Woman ,20),( Zhang Xiaogang , male ,19),( Zhang Xiaogang , male ,20),( Zhang Xiaogang , Woman ,19),( Zhang Xiaogang , Woman ,20)}
among ( Li Li , Woman ,20)、( Zhang Xiaogang , male ,19) Wait for tuples ,【 Zhang Xiaogang 】、【 male 】、【19】 Wait is the weight .D1、D2、D3 The Cartesian product of has 12 Tuples , That is, the cardinal number of Cartesian product is 12.D1、D2、D3 The Cartesian product of is represented by a two-dimensional table as follows :
surface 1 D1、D2、D3 Cartesian product of
full name | Gender | Age |
---|---|---|
Wang Ping | male | 19 |
Wang Ping | male | 20 |
Wang Ping | Woman | 19 |
Wang Ping | Woman | 20 |
Li Li | male | 19 |
Li Li | male | 20 |
Li Li | Woman | 19 |
Li Li | Woman | 20 |
Zhang Xiaogang | male | 19 |
Zhang Xiaogang | male | 20 |
Zhang Xiaogang | Woman | 19 |
Zhang Xiaogang | Woman | 20 |
(3) Relationship
The tuples contained in the Cartesian product of fields are obtained by any combination of elements in multiple fields , So many tuples have no practical significance . The set formed by selecting meaningful tuples from the Cartesian product of the field is called relation . The relationship is expressed as :
R(D1,D2,…,Dn)
among :R Is the name of the relationship .
A relationship is a two-dimensional table , Relation is a subset of Cartesian product .
for example : According to the actual situation from D1×D2×D3 Extract meaningful tuples from , Construct the relationship shown in the following table .
surface 2 Student relations
full name | Gender | Age |
---|---|---|
Wang Ping | male | 20 |
Li Li | Woman | 20 |
Zhang Xiaogang | male | 19 |
2、 Concepts involved in relationships
(1) Tuples
A row in the relationship is called a tuple , The elements that make up a tuple are called components . The relationship between entities can be represented by tuples . for example : surface 2 There are three tuples in , Corresponding to three student entities .
【 Wang Ping , male ,20】 It's a tuple , It contains three components , Namely 【 Wang Ping 】、【 male 】、【20】.
(2) attribute
A column in a relationship is called an attribute . Attributes have types and values , The type of attribute refers to the attribute name and value range , The value of the attribute refers to the specific value of the attribute . Attributes represent the characteristics of an entity . surface 2 There are three attributes in , Name, respectively 、 Gender and age .
(3) Candidate code and main code
If the attribute or attribute group in the relationship , Its value can uniquely identify a tuple , Then the attribute or attribute group is called candidate code (Candidate Key). When a relationship has multiple candidates , Select one of them as the main code (Primary Key), If a relationship has only one candidate , Then the candidate code is the main code . If a candidate code contains only one attribute , Call the candidate code single attribute code , If a candidate code contains multiple attributes , Then the candidate code is called multi-attribute code .
If it's on the watch 2 Add student ID to your student relationship , You can use the student number as the main code , If there is no student with the same name , Then the name can be used as a candidate .
(4) Primary and non primary
In relationship , The attributes contained in the candidate code are called primary attributes , Attributes that are not included in the candidate code are called non primary attributes . for example : In student relations , Student ID is the main attribute , Gender and age are non main attributes .
3、 The type of relationship
Tables in relational databases are divided into basic tables 、 There are three types of query tables and view tables .
(1) Basic table
A basic table is a table that actually exists in a relational database , Is the logical representation of the actual stored data . stay MySQL in , Use create table Command to create a basic table .
/* create table emp( s_id int primary key, s_name char(20), gender char(2), birth date, phone char(11) ); insert into emp values(1001,' Zhang min ',' Woman ','1995-3-4','13782594488'); insert into emp values(1002,' Wang Pengcheng ',' male ','1990-12-9','13736776666'); insert into emp values(1003,' Liu Weiwei ',' male ','1992-10-25','13542857766'); insert into emp values(1004,' Wangpenghui ',' Woman ','1996-8-10','13623569877'); insert into emp values(1005,' Liu Gang ',' male ','1989-9-14','13025669874'); insert into emp values(1006,' Zhang Jingjing ',' Woman ','1985-9-20','13203569855'); */
mysql> create table emp(
-> s_id int primary key,
-> s_name char(20),
-> gender char(2),
-> birth date,
-> phone char(11)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> insert into emp values(1001,' Zhang min ',' Woman ','1995-3-4','13782594488');
Query OK, 1 row affected (0.03 sec)
mysql> insert into emp values(1002,' Wang Pengcheng ',' male ','1990-12-9','13736776666');
Query OK, 1 row affected (0.01 sec)
mysql> insert into emp values(1003,' Liu Weiwei ',' male ','1992-10-25','13542857766');
Query OK, 1 row affected (0.00 sec)
mysql> insert into emp values(1004,' Wangpenghui ',' Woman ','1996-8-10','13623569877');
Query OK, 1 row affected (0.00 sec)
mysql> insert into emp values(1005,' Liu Gang ',' male ','1989-9-14','13025669874');
Query OK, 1 row affected (0.00 sec)
mysql> insert into emp values(1006,' Zhang Jingjing ',' Woman ','1985-9-20','13203569855');
Query OK, 1 row affected (0.01 sec)
mysql> select * from emp;
+------+-----------+--------+------------+-------------+
| s_id | s_name | gender | birth | phone |
+------+-----------+--------+------------+-------------+
| 1001 | Zhang min | Woman | 1995-03-04 | 13782594488 |
| 1002 | Wang Pengcheng | male | 1990-12-09 | 13736776666 |
| 1003 | Liu Weiwei | male | 1992-10-25 | 13542857766 |
| 1004 | Wangpenghui | Woman | 1996-08-10 | 13623569877 |
| 1005 | Liu Gang | male | 1989-09-14 | 13025669874 |
| 1006 | Zhang Jingjing | Woman | 1985-09-20 | 13203569855 |
+------+-----------+--------+------------+-------------+
6 rows in set (0.00 sec)
(2) Query table
Query table refers to the query results or temporary tables generated in the query . The data in the query table comes from the basic table .
/* select s_id, s_name, phone from emp where gender=' Woman '; */
mysql> select s_id, s_name, phone
-> from emp
-> where gender=' Woman ';
+------+-----------+-------------+
| s_id | s_name | phone |
+------+-----------+-------------+
| 1001 | Zhang min | 13782594488 |
| 1004 | Wangpenghui | 13623569877 |
| 1006 | Zhang Jingjing | 13203569855 |
+------+-----------+-------------+
3 rows in set (0.01 sec)
(3) View table
A view table is a table derived from a base table or other view table . The view table is a virtual table , Views are defined in the database , The data seen through the view is the data stored in the basic table . The operation on the view is the same as that on the table , It can be queried 、 modify ( There are certain restrictions )、 Delete .
When you make changes to the data you see through the view , The data of the corresponding basic table will also change , meanwhile , If the data in the basic table changes , Then this change is automatically reflected in the view .
From the user's perspective , A view is to view the data in the database from a specific perspective . From the inside of the database system , A view is made up of SELECT A virtual table defined by a query composed of statements . From the inside of the database system , A view is composed of data in one or more tables , From the outside of the database system , A view is like a table , The general operations that can be performed on tables can be applied to views , For example, query , Insert , modify , Delete operation, etc .
/* create view v_1 as select s_id, s_name, phone from emp where gender=' Woman '; */
mysql> create view v_1
-> as
-> select s_id, s_name, phone
-> from emp
-> where gender=' Woman ';
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+----------------+
| Tables_in_mydb |
+----------------+
| emp |
| v_1 |
+----------------+
2 rows in set (0.00 sec)
mysql> select * from v_1;
+------+-----------+-------------+
| s_id | s_name | phone |
+------+-----------+-------------+
| 1001 | Zhang min | 13782594488 |
| 1004 | Wangpenghui | 13623569877 |
| 1006 | Zhang Jingjing | 13203569855 |
+------+-----------+-------------+
3 rows in set (0.00 sec)
4、 The nature of the basic relationship
A relationship is a two-dimensional table , But a two-dimensional table is not necessarily a relationship . A two-dimensional table only satisfies the basic properties of the relationship , Is a relationship . The nature of the relationship is as follows :
(1) The data of the same attribute has homogeneity
The so-called homogeneity means that an attribute has the same data type 、 The value range is the same .
(2) Attribute names in relationships cannot be duplicate
In a relationship , Attributes are distinguished by attribute names , Therefore, attribute names cannot be repeated . The attributes of different relationships can be the same , For example, there are name attributes in the student table , The teacher table can also have name attributes .
(3) Tuples in a relationship cannot be repeated
Two identical tuples cannot be reproduced in a relationship . This is because entities are represented by tuples in relationships , If there are duplicate tuples, it means that the information of an entity is saved repeatedly . therefore , Duplicate tuples cannot appear in a relationship , Ensure the uniqueness of entities .
(4) Tuples in relation are order independent
The order of tuples in a relationship can be exchanged arbitrarily , therefore , For the convenience of viewing data , You can sort the data arbitrarily .
(5) The attributes in the relationship are order independent
The order of columns in the relationship can be exchanged arbitrarily , If the number and nature of two relationship attributes are the same , Only the order of attributes is different , Then the structure of these two relations is the same .
(6) Every component of the relationship must be indivisible
The normalization of relationship requires that the relationship pattern must meet certain conditions , One of the most basic is that each component of the relationship must be an inseparable data item . for example , The telephone of employee relationship can be divided into home phone and office phone, which does not meet the basic requirements of relationship standardization . As shown in the table 3 Shown .
For tables 3 Attribute phone in , It can be directly decomposed into two attributes: office phone and home phone . As shown in the table 4 Shown .
5、 Relationship model
A relationship pattern is a description of a relationship . The relational pattern can be expressed as :
R(U,D,Dom,F)
among :
R: Relationship name
U: Collection of properties
D: Domain of property
Dom: Attribute to a collection of domain images
F: A collection of data dependencies
The relational schema can be simplified as :R(U) or R(A1,A2,…,An)
among :R Name the relationship ,A1,A2,…,An For the property name .
6、 relational database
A database based on a relational model is called a relational database . In a relational database , The relationship between entities is expressed by relationship . among , A relationship corresponds to a set of entities , A row in the relationship corresponds to an entity , A column in the relationship corresponds to an attribute of the entity .
Two 、 Relationship operation
1、 The basic content of relationship operation
Relational operations include data query 、 Data maintenance and data control . Data query includes data retrieval 、 Statistics 、 Sort 、 grouping ; Data maintenance includes data addition 、 Delete and modify ; Data control is the function of data access control and concurrency control to ensure the safety and integrity of data . Relational operations can use union in relational algebra 、 hand over 、 Bad 、 choice 、 Projection 、 The cartesian product 、 Connect 、 There are eight operations to express . There is no 、 Bad 、 choice 、 Five basic operations of the relation between projection and Cartesian product .
2、 Characteristics of relationship operation
(1) Relational operation language integration : Relational operation language commonly used is SQL(Structural Query Language) Language , With data definition 、 Inquire about 、 The integration of update and control . Relational operation language can be embedded into the host language as host language , It can also be used as an independent language . These characteristics of relational operation language make relational operation language easy to learn 、 Easy to use .
(2) The way of relational operation is set operation : Initial data of relation operation 、 Intermediate data and result data are a set of tuples .
(3) Relational operation language is a highly non procedural language : When users use relational operation language , Just point out what to do , There is no need to point out how to do , Selection of data access path 、 The choice and optimization of data operation methods are determined by DBMS Done automatically . This highly non procedural feature of relational operation language makes the use of relational database management system very simple .
3、 ... and 、 The integrity of the relationship
The integrity of relational model is to restrict and restrict the data in the relationship . The relational model supports three types of integrity constraints : Entity integrity 、 Referential integrity and user-defined integrity . Among them, entity integrity and reference integrity are the integrity constraints that the relational model must meet , from DBMS Automatic support . User defined integrity means that integrity rules are defined by users according to their needs .
1、 Entity integrity
Entity integrity rules : If the property A It's the relationship R The main attribute of , Property A The value of cannot be null .
(1) Entity integrity ensures the uniqueness of entities . Take code as the identification of entity or connection in relation , The primary attribute cannot be empty to ensure the uniqueness of the entity or connection .
(2) Entity integrity can ensure the distinguishability of entities . Null value uses NULL Express , If the primary attribute is empty , Then it indicates that there is an unidentifiable entity . for example : The student number of the student table is the main attribute , Then the student number cannot be null .
/* create table dept( dept_id int primary key, dept_name char(20), phone char(20) ); */
mysql> create table dept(
-> dept_id int primary key, -- Definition dept_id Main code
-> dept_name char(20),
-> phone char(20)
-> );
Query OK, 0 rows affected (0.01 sec)
-- insert data
-- The primary code is not empty , Insert the success
mysql> insert into dept values(11,' Management Department ','3040255');
Query OK, 1 row affected (0.00 sec)
-- The primary code is empty , Insert the failure
mysql> insert into dept values(null,' Department of Economics ','3040266');
ERROR 1048 (23000): Column 'dept_id' cannot be null
-- Insert duplicate primary code values , Insert the failure
mysql> insert into dept values(11,' Department of Economics ','3040266');
ERROR 1062 (23000): Duplicate entry '11' for key 'PRIMARY'
2、 Referential integrity
(1) The representation of connections in relationships
In a relational database , Entity sets are represented by relationships . The relationship between entities is represented as follows :
(A) One to one contact : Adding the main code of one relationship to the other relationship can represent the one-to-one relationship of the two relationships . for example : The relationship between the college and the dean is one-to-one , You can put 【 college 】 The main code of the table 【 College number 】 Add to 【 dean 】 surface , Also can put the 【 dean 】 The main code of the table 【 Dean No 】 Add to 【 college 】 surface , As shown in the following table .
(B) One to many connection : First determine which relationship is 【 One 】、 Which relationship is 【 many 】, for example : The relationship between class and students is one to many , Then the class table is one to many 【 One 】 Fang , Also known as 【 Parent table 】, The student list is one to many connected 【 many 】 Fang , Also known as 【 Sub table 】. To express one to many connection , You need to add the main code of the parent table to the child table , That is, the parent table 【 class 】 Tabular 【 Class number 】 Add sub table 【 Student 】 in , In the student list 【 Class number 】 Called student table 【 Outer code 】. As shown in the following table .
(C) Many to many contact : Relational databases cannot directly represent many to many relationships . To express many to many contact , Need to add a new table , Add the main codes in the table with many to many connections to the new table . for example : Student schedule and curriculum have many to many connections , Then create a new elective table , Add the student number and the course number of the course to the elective table . The elective course includes two foreign codes : Student number , Course number . As shown in the following table .
(2) Refer to integrity rules
Add the main code of the parent table with one to many connections to the child table , Called outer code . One to one connection can be regarded as a special case of one to many connection , And many to many connections are finally transformed into many one to many connections . therefore , We can focus on one to many connections . For two relationships with one to many connections , The outer code is in the sub table , The parent table is called the referenced relationship , Sub tables are called reference relationships .
Refer to integrity rules : The referential integrity rule is used to limit the value of foreign codes in the sub table , The value of the outer code in the child table can be null or equal to the value of a main code in the parent table . For example, the value of class attribute in the student table , Or it's empty , Or choose from the class number in the class table .
/* create table class( class_id char(5) primary key, class_name char(20) ); create table stu( stu_id char(11) primary key, stu_name char(20), gender char(2), phone char(11), class_id char(5), foreign key(class_id) references class(class_id) ); */
mysql> create table class(
-> class_id char(5) primary key,
-> class_name char(20)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> create table stu(
-> stu_id char(11) primary key,
-> stu_name char(20),
-> gender char(2),
-> phone char(11),
-> class_id char(5),
-> foreign key(class_id) references class(class_id) -- Define foreign code
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into class values('C0001',' logistics 201 class '),('C0002',' logistics 202 class '),('C0003',' logistics 203 class ');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from class;
+----------+--------------+
| class_id | class_name |
+----------+--------------+
| C0001 | logistics 201 class |
| C0002 | logistics 202 class |
| C0003 | logistics 203 class |
+----------+--------------+
3 rows in set (0.00 sec)
-- stay stu Insert data into the table
-- class_id Null value , Insert the success
mysql> insert into stu values('20200224101',' zhang ',' male ','15937321588',null);
Query OK, 1 row affected (0.01 sec)
-- class_id from class Select from the table , Insert the success
mysql> insert into stu values('20200224102',' Zhang Jing ',' Woman ','13637321588','C0001');
Query OK, 1 row affected (0.01 sec)
-- class_id Insert a class Values that do not exist in the table , Insert the failure
mysql> insert into stu values('20200224103',' Li Hua ',' Woman ','13688332525','C0004');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`mydb`.`stu`, CONSTRAINT `stu_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `class` (`cl ass_id`))
3、 User-defined integrity
User defined integrity refers to the constraints defined for a specific application . Entity integrity and referential integrity are determined by DBMS Automatically guaranteed . The data constraint rules of user-defined integrity are defined by users according to actual needs . For example, according to the requirements of performance management , Students' grades are 0 To 100 Between .
边栏推荐
- 盘点JS判断空对象的几大方法
- Present pod information to the container through environment variables
- When sink is consumed in mysql, the self incrementing primary key has been set in the database table. How to operate in Flink?
- 【滤波跟踪】捷联惯导纯惯导解算matlab实现
- Sonar:Cognitive Complexity认知复杂度
- La voie du succès de la R & D des entreprises Internet à l’échelle des milliers de personnes
- Superscalar processor design yaoyongbin Chapter 10 instruction submission excerpt
- Introduction and application of smoothstep in unity: optimization of dissolution effect
- 软件内部的定时炸弹:0-Day Log4Shell只是冰山一角
- Steps of redis installation and self startup configuration under CentOS system
猜你喜欢
108. Network security penetration test - [privilege escalation 6] - [windows kernel overflow privilege escalation]
<No. 9> 1805. 字符串中不同整数的数目 (简单)
Flet教程之 18 Divider 分隔符组件 基础入门(教程含源码)
人大金仓受邀参加《航天七〇六“我与航天电脑有约”全国合作伙伴大会》
Flet tutorial 17 basic introduction to card components (tutorial includes source code)
[neural network] convolutional neural network CNN [including Matlab source code 1932]
<No. 8> 1816. Truncate sentences (simple)
An error occurred when vscade tried to create a file in the target directory: access denied [resolved]
Swiftui tutorial how to realize automatic scrolling function in 2 seconds
数据库系统原理与应用教程(007)—— 数据库相关概念
随机推荐
Stm32f1 and stm32subeide programming example -max7219 drives 8-bit 7-segment nixie tube (based on SPI)
Introduction to three methods of anti red domain name generation
110. Network security penetration test - [privilege promotion 8] - [windows sqlserver xp_cmdshell stored procedure authorization]
Detailed explanation of debezium architecture of debezium synchronization
MATLAB實現Huffman編碼譯碼含GUI界面
【神经网络】卷积神经网络CNN【含Matlab源码 1932期】
免备案服务器会影响网站排名和权重吗?
Rationaldmis2022 advanced programming macro program
Camera calibration (1): basic principles of monocular camera calibration and Zhang Zhengyou calibration
Fleet tutorial 19 introduction to verticaldivider separator component Foundation (tutorial includes source code)
【纹理特征提取】基于matlab局部二值模式LBP图像纹理特征提取【含Matlab源码 1931期】
Swiftui swift internal skill how to perform automatic trigonometric function calculation in swift
Completion report of communication software development and Application
小红书微服务框架及治理等云原生业务架构演进案例
The Oracle message permission under the local Navicat connection liunx is insufficient
How to understand the clothing industry chain and supply chain
ES底层原理之倒排索引
【全栈计划 —— 编程语言之C#】基础入门知识一文懂
百度数字人度晓晓在线回应网友喊话 应战上海高考英语作文
What is a LAN domain name? How to parse?