There is only so much about SQL statements

Chapter 1 Introduction to SQL

1.1 what is sql

  • SQL: Structure Query Language. (Structured query language), operate the database through sql (operation database, operation table, operation data)
  • SQL was identified by the American National Institute of Standards (ANSI) as the American standard for relational database languages, and was later adopted by the International Standards Organization (ISO) as an international standard for relational database languages.
  • All database vendors (MySql, oracle, sql server) support the ISO SQL standard.
  • Each database vendor has made its own extensions on the basis of the standard. Each database has its own specific syntax

1.2 Classification of sql

  • Data Definition Language (DDL data definition language) such as: operating database, operating table
  • Data Manipulation Language (DML data manipulation language), such as: adding, deleting, and modifying records in a table
  • Data Query Language (DQL data query language), such as: query operations on data in tables
  • Data Control Language (DCL Data Control Language), such as: setting user permissions

1.3 MySQL syntax specifications and requirements

(1) mysql's sql syntax is not case sensitive

MySQL's keywords and function names are not case-sensitive, but whether data values ​​are case-sensitive or not is related to character sets and collation rules.

ci (case-insensitive), cs (case-sensitive), _bin (binary, that is, the comparison is based on the value of the character encoding and has nothing to do with the language, case-sensitive)

(2) When naming: try to use 26 English letters in upper and lower case, numbers 0-9, underscore, do not use other symbols user_id

(3) It is recommended not to use mysql keywords as table names, field names, etc. If you accidentally use them, please use ` (floating sign) in the SQL statement to cause

(4) Do not contain spaces between object names such as database and table names, field names, etc.

(5) In the same mysql software, databases cannot have the same name, in the same library, tables cannot have the same name, and in the same table, fields cannot have the same name

(6) Punctuation marks:

must be in pairs

The lower half-width input method must be in English

String and date types can use single quotes ''

The alias of the column can use double quotes "", and do not use double quotes for the alias of the table name. as can be omitted when taking an alias

If the alias of the column does not contain spaces, the double quotes can be omitted, if there are spaces, the double quotes cannot be omitted.

(7) How to add comments in SQL scripts

Single-line comment: #comment content

Single-line comment: – space comment content where – the space behind must have

Multi-line comment: /* comment content */

#以下两句是一样的,不区分大小写
show databases;
SHOW DATABASES;

#创建表格
#create table student info(...); #表名错误,因为表名有空格
create table student_info(...); 

#其中name使用``飘号,因为name和系统关键字或系统函数名等预定义标识符重名了。
CREATE TABLE t_stu(
    id INT,
    `name` VARCHAR(20)
);

select id as "编号", `name` as "姓名" from t_stu; #起别名时,as都可以省略
select id as 编号, `name` as 姓名 from t_stu; #如果字段别名中没有空格,那么可以省略""
select id as 编 号, `name` as 姓 名 from t_stu; #错误,如果字段别名中有空格,那么不能省略""

Chapter 2 - DDL Operation Database

2.1 Create a database (master)

  • grammar
create database 数据库名 [character set 字符集][collate  校对规则]     注: []意思是可选的意思

Character set (charset): is a set of symbols and encodings.

  • practise

Create a database of day01 (default character set)

create database day01;

Create a day01_2 database, specify the character set as gbk (understand)

create database day01_2 character set gbk;

2.2 View all databases

2.2.1 View all databases

  • grammar
show databases; 

2.2.2 View the definition structure of the database 【understand】

  • grammar
show create database 数据库名;
  • View the definition of the database day01
show create database day01; 

2.3 Delete the database

  • grammar
drop database 数据库名;
  • Delete the day01_2 database
drop database day01_2;

2.4 Modify the database 【understand】

  • grammar
alter database 数据库名 character set 字符集;
  • Modify the character set (gbk) of the database of day01
alter database day01 character set gbk;

Notice:

  • is utf8, not utf-8
  • not modify the database name

2.5 Other operations

  • Switch database, select which database
use 数据库名;   		//注意: 在创建表之前一定要指定数据库. use 数据库名
  • Exercise: use day01
use day01;
  • Check the database in use
select database();

Chapter 3 - DDL Operation Table

3.1 Create table

3.1.1 Syntax

create table 表名(
	列名 类型 [约束],
	列名 类型 [约束]
	...
		
);

3.1.2 Type

3.1.2.1 Numeric types

  • Integer series: xxxInt

int(M), must be used with unsigned zerofill to make sense

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-8kBz3iew-1638520841000)(imgs/1560933629123.png)]

  • Floating point series: float, double (or real)

double(M,D): Indicates that the longest is M digits, of which D digits after the decimal point

For example: the data range represented by double(5,2) [-999.99,999.99], if it exceeds this range, an error will be reported.

  • Fixed-point series: decimal (the bottom layer is actually stored using strings)

decimal(M,D): Indicates that the longest is M digits, of which D digits after the decimal point

  • Bit type: bit

The byte range is: 1-8, the value range is: bit(1)~bit(64), the default bit(1)

Used to store binary numbers. For bit fields, using the select command directly will not see the result. It can be read using the bit() or hex() functions. When inserting a field of bit type, use the bit() function to convert it into a binary value before inserting, because the binary code is "01".

3.1.2.2 Datetime type

Date time type: year, date, datetime, timestamp

Pay attention to the representation range of each date and time

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-K8WWW1HO-1638520841002)(imgs/1560933691657.png)]

The difference between timestamp and datetime:

  • The timestamp range is relatively small
  • timestamp is related to time zone
    • show variables like ‘time_zone’;
    • set time_zone = ‘+8:00’;
  • timestamp is greatly affected by the MySQL version and the SQLMode of the server
  • If the first non-empty timestamp field in the table is inserted and updated as NULL, it will be automatically set to the system time

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-jXNxTuad-1638520841003)(imgs/image-20200406171844833.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-MznPFSM6-1638520841008)(imgs/image-20200406171900814.png)]

3.1.2.3 String type

MySQL provides a variety of storage types for character data, and different versions may be different. The common ones are:

char, varchar, xxtext, binary, varbinary, xxblob, enum, set, etc.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Ds5F1r7Y-1638520841015)(imgs/image-20200406180437224.png)]

  • String type char, varchar(M)

char If no width is specified, the default is 1 character

varchar(M), width must be specified

  • binary and varbinary are similar to char and varchar except that they contain binary strings and do not support things like fuzzy queries.

  • Generally, when saving a small number of strings, we will choose char and varchar; when saving large text, we usually choose to use text or blob series. Blob and text values ​​will cause some performance problems, especially when a large number of delete operations are performed, a large "hole" will be left in the data table. In order to improve performance, it is recommended to use the optimize table function on such tables regularly Do defragmentation. Synthetic (Synthetic) indexes can be used to improve the query performance of large text fields. If you need to perform fuzzy queries on large text fields, MySql provides prefix indexes. But still avoid retrieving large blob or text values ​​when not necessary.

  • enum enumeration type, its value range needs to be explicitly specified by enumeration when creating a table, for an enumeration with 1~255 members, 1 byte of storage is required; for 255`65535 members, 2 bytes of storage are required . For example: gender enum('male','female'). If a value other than the enumeration value is inserted, it will be processed as the first value. Only one of the enumeration values ​​can be selected at a time.

  • The set collection type can contain 0~64 members. Multiple members can be selected from a set at a time. If a set of 1-8 members is selected, it takes up 1 byte, 2 and 3 in turn. . 8 bytes. For example: hoppy set('eating','sleeping','playing games','traveling'), when selecting 'eating, sleeping' or 'sleeping, playing games, traveling'

3.1.2.4 Examples

+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| eid            | int(11)      | NO   | PRI | NULL    | auto_increment |
| ename          | varchar(20)  | NO   |     | NULL    |                |
| tel            | char(11)     | NO   |     | NULL    |                |
| gender         | char(1)      | YES  |     | 男        |                |
| salary         | double       | YES  |     | NULL    |                |
| commission_pct | double(3,2)  | YES  |     | NULL    |                |
| birthday       | date         | YES  |     | NULL    |                |
| hiredate       | date         | YES  |     | NULL    |                |
| job_id         | int(11)      | YES  |     | NULL    |                |
| email          | varchar(32)  | YES  |     | NULL    |                |
| mid            | int(11)      | YES  |     | NULL    |                |
| address        | varchar(150) | YES  |     | NULL    |                |
| native_place   | varchar(10)  | YES  |     | NULL    |                |
| did            | int(11)      | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

3.1.3 Constraints

  • That is, rules, rules and regulations;
  • Role: to ensure that the data inserted by the user is saved in the database in compliance with the specification
constraint constraint keyword
primary key primary key Non-empty and unique, and a table can only have one primary key
only unique Unique, the same data cannot appear in the current column
non empty not null Not empty, the current column cannot be null
default default Specifies the default data if the current column has no data

Constraint Type:

  • not null: non-empty; eg: username varchar(40) not null username This column cannot have a null value

  • unique: unique constraint, the following data cannot be repeated with the previous; eg: cardNo char(18) unique; there cannot be repeated data in the cardNo column

  • primary key; primary key constraint (not empty + unique); generally used on the id column of the table. A table basically has an id column, and the id column is used as a unique identifier

    • auto_increment: Automatic growth, you must set the primary key before you can use auto_increment
  • id int primary key auto_increment; id does not need to be maintained by ourselves. When inserting data, insert null directly, and automatically grow and fill in to avoid duplication.

Notice:

  1. First set the primary key and then set auto_increment
  2. Null can be inserted only when auto_increment is set, otherwise an error will be reported when inserting null

id column:

  1. Set id to int type, add primary key constraint, and auto-grow
  2. Or set the id to a string type, add a primary key constraint, and cannot set automatic growth

3.1.4 Exercises

  • Create a student table (with an id field, the name field cannot be repeated, the gender field cannot be empty, the default value is male, and the id primary key automatically grows)
CREATE TABLE student(
	id INT PRIMARY KEY AUTO_INCREMENT, -- 主键自增长
	NAME VARCHAR(30) UNIQUE, -- 唯一约束
	gender CHAR(1) NOT NULL DEFAULT '男'
);

3.2 Check the table [understand]

3.2.1 View all tables

show tables;

3.2.2 View the definition structure of the table

  • grammar

    desc table name;

  • Exercise: View the definition structure of the student table

desc student;

3.3 Modify table【Master, but don't memorize】

3.3.1 Grammar

  • add a column
alter table 【数据库名.]表名称 addcolumn】 字段名 数据类型;
alter table 【数据库名.]表名称 addcolumn】 字段名 数据类型 first;
alter table 【数据库名.]表名称 addcolumn】 字段名 数据类型 after 另一个字段;
  • Modify the type constraint of the column:alter table 表名 modify 字段 类型 约束 ;
  • Modify column names, types, constraints:alter table 表名 change 旧列 新列 类型 约束;
  • Delete a column:alter table 表名 drop 列名;
  • Modify the table name:rename table 旧表名 to 新表名;

3.3.2 Exercises

  • Add a grade field to the student table, the type is varchar(20), it cannot be empty
ALTER TABLE student ADD grade VARCHAR(20) NOT NULL;
  • Change the gender field of the student table to an int type, which cannot be empty, and the default value is 1
alter table student modify gender varchar(20);
  • Change the grade field of the student table to a class field
ALTER TABLE student CHANGE grade class VARCHAR(20) NOT NULL;
  • Delete the class field
ALTER TABLE student DROP class;
  • Change the student table to the teacher table (understand)
RENAME TABLE student TO teacher;

3.4 Delete table【Master】

  • grammar

    drop table table name;

  • Delete the teacher table

drop table teacher;

Chapter 4 - DML Operation Table Records - Additions, Deletions, and Modifications [Key Points]

  • Preparations: Create a commodity table (commodity id, commodity name, commodity price, commodity quantity.)
create table product(
	pid int primary key auto_increment,
	pname varchar(40),
	price double,
	num int
);

4.1 Insert record

4.1.1 Syntax

  • Method 1: Insert the specified column. If the column is not listed, it will be automatically assigned as null .

    eg: just want to insert pname, price, insert into t_product(pname, price) values('mac',18000);

insert into 表名(列,列..) values(值,值..);

Note: If no column is inserted and a non-null constraint is set, an error will be reported

  • Method 2: Insert all columns, if a column does not want to insert a value, you need to assign a value of null
insert into 表名 values(,....);           

eg:
insert into product values(null,'苹果电脑',18000.0,10);
insert into product values(null,'华为5G手机',30000,20);
insert into product values(null,'小米手机',1800,30);
insert into product values(null,'iPhonex',8000,10);
insert into product values(null,'iPhone7',6000,200);
insert into product values(null,'iPhone6s',4000,1000);
insert into product values(null,'iPhone6',3500,100);
insert into product values(null,'iPhone5s',3000,100);

insert into product values(null,'方便面',4.5,1000);
insert into product values(null,'咖啡',11,200); 
insert into product values(null,'矿泉水',3,500);

4.2 Update records

4.2.1 Grammar

update 表名 set 列 =值, 列 =值 [where 条件]

4.2.2 Exercises

  • Modify the price of all products to 5000 yuan
update product set price = 5000;
  • Change the price of the product name to Apple Computer to 18,000 yuan
UPDATE product set price = 18000 WHERE pname = '苹果电脑';
  • Change the product name to Apple Computer, change the price to 17000, and change the quantity to 5
UPDATE product set price = 17000,num = 5 WHERE pname = '苹果电脑';
  • Increase the price of the product whose product name is instant noodles by 2 yuan on the original basis
UPDATE product set price = price+2 WHERE pname = '方便面';

4.3 Deleting records

4.3.1 delete

According to the conditions, delete data one by one

  • grammar
delete from 表名 [where 条件]    注意: 删除数据用delete,不用truncate
  • type

Delete the record named 'Apple Computer' in the table

delete from product where pname = '苹果电脑';

Delete commodity records whose price is less than 5001

delete from product where price < 5001;

Delete all records in the table (it is generally not recommended to use the delete statement to delete, the delete statement is executed line by line, the speed is too slow)

delete from product;

4.3.2 truncated

DROP the table directly, and then create the same new table. Deleted data cannot be retrieved. Executes faster than DELETE

truncate table 表;

4.3.3 Delete data during work

  • Physical deletion: it is actually deleted, the data is not there, and using delete is a physical deletion
  • Logical deletion: There is no real deletion, the data is still there. Make a mark, in fact, logical deletion is an update eg: state 1 enable 0 disable

Chapter 5 - DQL Operation Table Record - Query [Key Points]

5.1 Basic query syntax

select 要查询的字段名 from 表名 [where 条件] 

5.2 Simple query

5.2.1 Query records of all rows and columns

  • grammar
select * form 表
  • Query all columns in the product table
select * from product;

5.2.2 Query the records of a specific column in a table

  • grammar
select 列名,列名,列名... from 表
  • Query product name and price
select pname, price from product;

5.2.3 Deduplication query distinct

  • grammar
SELECT DISTINCT 字段名 FROM 表名;   //要数据一模一样才能去重
  • Deduplicate the name of the query product
SELECT DISTINCT pname,price FROM product

Note: Deduplication is aimed at a certain column, and the column name cannot appear before the distinct

5.2.4 Alias ​​query

  • grammar
select 列名 as 别名 ,列名  from 表   //列别名  as可以不写
select 别名.* from 表 as 别名      //表别名(多表查询, 明天会具体讲)
  • To query product information, use an alias
SELECT pid ,pname AS '商品名',price AS '商品价格',num AS '商品库存' FROM product

5.2.5 Operation query (+,-,*,/,% etc.)

  • Query the product name and product price +10: we can add a fixed value to a certain field, and perform operations on multiple fields
select pname ,price+10 as 'price' from product;

select name,chinese+math+english as total from student

Notice

  • Operational query field, between fields is possible
  • Types such as strings can be used for operation queries, but the results are meaningless

5.3 Conditional query (very important)

5.3.1 Syntax

select ... from 表 where 条件 
//取出表中的每条数据,满足条件的记录就返回,不满足条件的记录不返回

5.3.2 Operators

1. Comparison operators

大于:>
小于:<
大于等于:>=
小于等于:<=
等于:=   不能用于null判断
不等于:!=  或 <>
安全等于: <=>  可以用于null值判断

2. Logical operators (it is recommended to use words, in terms of readability)

逻辑与:&& 或 and
逻辑或:|| 或 or
逻辑非:! 或 not
逻辑异或:^ 或 xor

3. Scope

区间范围:between x  and  y
	    not between x  and  y
集合范围:in (x,x,x) 
	    not  in (x,x,x)

4. Fuzzy query and regular matching (only for string type, date type)

like 'xxx'  模糊查询是处理字符串的时候进行部分匹配
如果想要表示0~n个字符,用%
如果想要表示确定的1个字符,用_
regexp '正则'

5. Special null value handling

#(1)判断时
xx is null
xx is not null
xx <=> null
#(2)计算时
ifnull(xx,代替值) 当xx是null时,用代替值计算

5.3.3 Exercises

  • Query products whose price is more than 3000
select * from product where price > 3000;
  • Query the product with pid=1
select * from product where pid = 1;
  • Query the product with pid<>1 (!=)
select * from product where pid <> 1;
  • Query for products with prices between 3000 and 6000
select * from product where price between 3000 and 6000;
  • Query products whose pid is in the range of 1, 5, 7, 15
select * from product where id = 1;
select * from product where id = 5;
select * from product where id = 7;
select * from product where id = 15;

select * from product where id in (1,5,7,15);
  • Query products whose product name starts with iPho (iPhone series)
select * from product where pname like 'iPho%';
  • Query items whose price is greater than 3000 and whose quantity is greater than 20 (condition and condition and...)
select * from product where price > 3000 and num > 20;
  • Query items with id=1 or price less than 3000
select * from product where pid = 1 or price < 3000;

5.4 Sorting queries

Sorting is written after the query, which means that the data is queried and then sorted

5.4.1 Environment preparation

# 创建学生表(有sid,学生姓名,学生性别,学生年龄,分数列,其中sid为主键自动增长)
CREATE TABLE student(
	sid INT PRIMARY KEY auto_increment,
	sname VARCHAR(40),
	sex VARCHAR(10),
	age INT,
    score DOUBLE
);

INSERT INTO student VALUES(null,'zs','男',18,98.5);
INSERT INTO student VALUES(null,'ls','女',18,96.5);
INSERT INTO student VALUES(null,'ww','男',15,50.5);
INSERT INTO student VALUES(null,'zl','女',20,98.5);
INSERT INTO student VALUES(null,'tq','男',18,60.5);
INSERT INTO student VALUES(null,'wb','男',38,98.5);
INSERT INTO student VALUES(null,'小丽','男',18,100);
INSERT INTO student VALUES(null,'小红','女',28,28);
INSERT INTO student VALUES(null,'小强','男',21,95);

5.4.2 Single Column Sorting

  1. Syntax: Sort only by a certain field, sort by a single column
SELECT 字段名 FROM 表名 [WHERE 条件] ORDER BY 字段名 [ASC|DESC];  //ASC: 升序,默认值; DESC: 降序
  1. Case: Query all students in descending order of scores
SELECT * FROM student ORDER BY score DESC

5.4.3 Combination sorting

  1. Syntax: sort multiple fields at the same time, if the first field is equal, sort by the second field, and so on
SELECT 字段名 FROM 表名 WHERE 字段=值 ORDER BY 字段名1 [ASC|DESC], 字段名2 [ASC|DESC];
  1. Exercise: Query all students in descending order of scores, if the scores are the same, then in descending order of age
SELECT * FROM student ORDER BY score DESC, age DESC

5.5 Aggregate functions

Aggregate functions are used for statistics, and are usually used together with grouping queries to count the data of each group

5.5.1 List of aggregate functions

aggregate function effect
max(column name) Find the maximum value of this column
min(column name) Find the minimum value of this column
avg(column name) Find the average of this column
count(column name) Count how many records there are in this column
sum(column name) sum this column
  1. grammar
SELECT 聚合函数(列名) FROM 表名 [where 条件];
  1. the case
-- 求出学生表里面的最高分数
SELECT MAX(score) FROM student
-- 求出学生表里面的最低分数
SELECT MIN(score) FROM student
-- 求出学生表里面的分数的总和(忽略null值)
SELECT SUM(score) FROM student
-- 求出学生表里面的平均分
SELECT AVG(score) FROM student
-- 求出学生表里面的平均分(缺考了当成0分处理)
SELECT AVG(IFNULL(score,0)) FROM student
-- 统计学生的总人数 (忽略null) 
SELECT COUNT(sid) FROM student
SELECT COUNT(*) FROM student

Note: Aggregate functions ignore NULL values

We found that NULL records will not be counted. It is recommended not to use columns that may be null if the number is counted, but what if NULL needs to be counted? We can solve this problem by IFNULL(column name, default value) function. If the column is not null, return the value of this column. If NULL, the default value is returned.

-- 求出学生表里面的平均分(缺考了当成0分处理)
SELECT AVG(IFNULL(score,0)) FROM student;

5.6 Group query

GROUP BY treats the same content in the grouping field results as a group, and returns the first piece of data in each group, so grouping alone is useless. The purpose of grouping is for statistics. Generally, grouping will be used together with aggregation functions

5.6.1 Grouping

  1. grammar
SELECT 字段1,字段2... FROM 表名  [where 条件] GROUP BY[HAVING 条件];
  1. the case
-- 根据性别分组, 统计每一组学生的总人数
SELECT sex '性别',COUNT(sid) '总人数' FROM student GROUP BY sex

-- 根据性别分组,统计每组学生的平均分
SELECT sex '性别',AVG(score) '平均分' FROM student GROUP BY sex

-- 根据性别分组,统计每组学生的总分
SELECT sex '性别',SUM(score) '总分' FROM student GROUP BY sex

5.6.2 Filter having after grouping

The condition after grouping cannot be written after where, the where keyword should be written before group by

  • According to gender grouping, count the total number of students in each group > 5 (screening after grouping)
SELECT sex, count(*) FROM student GROUP BY sex HAVING count(sid) > 5
  • According to gender grouping, only the age is greater than or equal to 18, and the number of people in the group is required to be greater than 4
SELECT sex '性别',COUNT(sid) '总人数' FROM student WHERE age >= 18 GROUP BY sex HAVING COUNT(sid) > 4

5.6.3 The difference between where and having [Interview]

child name effect
where child clause 1) Before grouping the query results, remove the rows that do not meet the where condition, that is, filter the data before grouping, that is, filter first and then group. 2) Aggregation functions cannot be used after where
having clause 1) The function of the having clause is to filter the groups that meet the conditions, that is, filter the data after grouping, that is, group first and then filter. 2) Aggregation functions can be used after having

5.7 Pagination query

5.7.1 Syntax

select ... from .... limit a ,b
LIMIT a,b;
a represents the number of skipped data
b represents the number of data to be queried

5.7.2 Case

-- 分页查询
-- limit 关键字是使用在查询的后边,如果有排序的话则使用在排序的后边
-- limit的语法: limit offset,length  其中offset表示跳过多少条数据,length表示查询多少条数据
SELECT * FROM product LIMIT 0,3
-- 查询product表中的前三条数据(0表示跳过0条,3表示查询3条)

SELECT * FROM product LIMIT 3,3
-- 查询product表的第四到六条数据(3表示跳过3条,3表示查询3条)
-- 分页的时候,只会告诉你我需要第几页的数据,并且每页有多少条数据
-- 假如,每页需要3条数据,我想要第一页数据: limit 0,3
-- 假如,每页需要3条数据,我想要第二页数据: limit 3,3
-- 假如,每页需要3条数据,我想要第三页数据: limit 6,3
-- 结论: length = 每页的数据条数,offset = (当前页数 - 1)*每页数据条数
-- limit (当前页数 - 1)*每页数据条数, 每页数据条数

5.8 Syntax Summary for Queries

select...from...where...group by...order by...limit

select...from...where...
select...from...where...order by...
select...from...where...limit...
select...from...where...order by...imit

Chapter 6 Three Paradigms of Databases

Good database design will have an important impact on data storage performance and later program development. Establishing a scientific and standardized database needs to meet some rules to optimize the design and storage of data. These rules are called paradigms.

6.1 First normal form: ensuring that each column remains atomic

First normal form is the most basic normal form. If all field values ​​in the database table are indecomposable atomic values, it means that the database table satisfies the first normal form.

The rational compliance of the first normal form needs to be determined according to the actual needs of the system. For example, some database systems need to use the "address" attribute. Originally, the "address" attribute should be directly designed as a field of a database table. However, if the system often accesses the "city" part of the "address" attribute, then the "address" attribute must be re-split into multiple parts such as province, city, and detailed address for storage. It will be very convenient for some operations. Only in this way can the design satisfy the first normal form of the database, as shown in the following table.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ckfYJvC2-1638521360056)(imgs/tu_11.png)]

If the first normal form is not followed, the query data needs further processing (query is inconvenient). Comply with the first normal form, and query any data that requires any field data (easy to query)

6.2 Second Normal Form: Make sure that every column in the table is related to the primary key

The second normal form is a further step on the basis of the first normal form. The second normal form needs to ensure that each column in the database table is related to the primary key, not only to a certain part of the primary key (mainly for the joint primary key). That is to say, in a database table, only one type of data can be stored in a table, and multiple types of data cannot be stored in the same database table.

For example, if you want to design an order information table, because there may be many kinds of goods in the order, you need to use the order number and product number as the joint primary key of the database table, as shown in the following table

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-TclGdISW-1638521360057)(imgs/tu_12.png)]

This creates a problem: In this table, the order number and the product number are used as the joint primary key. In this way, information such as the product name, unit, and product price in the table is not related to the primary key of the table, but only related to the product number. So the design principle of the second normal form is violated here.

And if the order information table is split, the product information is separated into another table, and the order item table is also separated into another table, it will be perfect. As follows


<img src="imgs/tu_13.png" style="zoom: 67%;" />

This design greatly reduces the redundancy of the database. If you want to obtain the product information of the order, use the product number to query in the product information table

6.3 Third Normal Form: Ensure that each column is directly related to the primary key column, not indirectly

The third normal form needs to ensure that each column of data in the data table is directly related to the primary key, not indirectly.

For example, when designing an order data table, the customer number can be used as a foreign key to establish a corresponding relationship with the order table. It is not possible to add fields about other customer information (such as name, company, etc.) to the order form. The design shown in the following two tables is a database table that satisfies the third normal form.


<img src="imgs/tu_14.png" style="zoom:67%;" />

In this way, when querying order information, the customer number can be used to refer to the records in the customer information table, and there is no need to enter the content of customer information in the order information table multiple times, reducing data redundancy

Chapter 7 Foreign Key Constraints

7.1 The concept of foreign key constraints

On the premise of following the three paradigms, we often have to split tables and store data in multiple tables to reduce redundant data. However, there is an associated relationship between the split tables and tables. We must use a constraint to agree on the relationship between the tables. This constraint is the foreign key constraint.

7.2 The role of foreign key constraints

The foreign key constraint is to ensure the referential integrity between one or two tables, and the foreign key is a referential relationship between two fields of a table or two fields of two tables.

7.3 Syntax for creating foreign key constraints

7.3.1 Specify foreign key constraints when creating tables

create table [数据名.]从表名(
	字段名1 数据类型  primary key ,
	字段名2 数据类型 ,
	....,
    [constraint 外键约束名] foreign key (从表字段) references 主表名(主表字段) [on update 外键约束等级][on delete 外键约束等级]
    #外键只能在所有字段列表后面单独指定
    #如果要自己命名外键约束名,建议 主表名_从表名_关联字段名_fk
);

7.8.2 Specifying foreign key constraints after table creation

alter table 从表名称 add [constraint 外键约束名] foreign key (从表字段名) references 主表名(主表被参照字段名) [on update xx][on delete xx];

7.4 Syntax for dropping foreign key constraints

ALTER TABLE 表名称 DROP FOREIGN KEY 外键约束名;
#查看约束名 SELECT * FROM information_schema.table_constraints WHERE table_name = '表名称';
#删除外键约束不会删除对应的索引,如果需要删除索引,需要用ALTER TABLE 表名称 DROP INDEX 索引名;
#查看索引名 show index from 表名称;

7.5 Requirements for foreign key constraints

  • Create a foreign key on the secondary table, and the primary table must exist first.

  • A table can create multiple foreign key constraints

  • Normally, the foreign key column of the slave table must point to the primary key column of the main table

  • The name of the foreign key column of the slave table and the referenced column of the main table can be different, but the data type must be the same

7.6 Foreign key constraint levels

  • Cascade mode: When updating/deleting records on the master table, update/delete the matching records from the slave table synchronously

  • Set null method: When updating/deleting records on the main table, set the column of the matching record on the slave table to null, but pay attention to the fact that the foreign key column of the sub-table cannot be not null

  • No action mode: If there is a matching record in the child table, update/delete operations on the corresponding candidate key of the parent table are not allowed

  • Restrict mode: Same as no action, both check foreign key constraints immediately

  • Set default method (may be blank in the visualization tool SQLyog): When the parent table is changed, the child table sets the foreign key column to a default value, but Innodb cannot recognize it

    If no level is specified, it is equivalent to the Restrict method

7.7 Foreign key constraints exercise

-- 部门表
create table dept( 
	id int primary key,
	dept_name varchar(50),
	dept_location varchar(50)
);
-- 员工表
CREATE TABLE emp(
	eid int primary key,
	name varchar(50) not null,
	sex varchar(10),
    dept_id int
);
-- 给员工表表的dept_id添加外键指向部门表的主键
alter table emp add foreign key(dept_id) references dept(id)

Chapter 8 Relationship Between Multiple Tables

8.1 One-to-many relationship

8.1.1 Concept

A one-to-many relationship means that one row of data in the master table can correspond to multiple rows of data in the slave table at the same time, and in turn, multiple rows of data in the slave table point to the same row of data in the master table.

8.1.2 Application scenarios

Category table and product table, class table and student table, user table and order table, etc.

8.1.2 Table creation principles

Use the one side as the main table, and the multi-side as the slave table, specify a field in the slave table as a foreign key, pointing to the primary key of the master table

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NGeGQWsp-1638521360059)(imgs/1536033119270.png)]

8.1.3 Create table statement practice

-- 创建分类表
CREATE TABLE category(
	cid INT PRIMARY KEY AUTO_INCREMENT,
	cname VARCHAR(50)
);

-- 创建商品表
CREATE TABLE product(
	pid INT PRIMARY KEY AUTO_INCREMENT,
	pname VARCHAR(50),
	price DOUBLE,
	cid INT
)
-- 给商品表添加一个外键
alter table product add foreign key(cid) references  category(cid)

8.2 Many-to-many relationships

8.2.1 Concept

Both tables are multi-row. A row of data in table A can correspond to multiple rows of data in table B at the same time. Conversely, a row of data in table B can also correspond to multiple rows of data in table A.

8.2.2 Application scenarios

Order table and product table, student table and course table, etc.

8.2.3 Table creation principles

Because the two tables are multi-party, foreign keys cannot be created in the two tables, so a new intermediate table needs to be created, and two fields are defined in the intermediate table. These two fields are used as foreign keys to point to the two tables respectively. primary key of

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-pVfaP80C-1638521360064)(imgs/tu_5.png)]

8.2.4 Create table statement practice

-- 创建学生表
CREATE TABLE student(
	sid INT PRIMARY KEY AUTO_INCREMENT,
	sname VARCHAR(50)
);

-- 创建课程表
CREATE TABLE course(
	cid INT PRIMARY KEY AUTO_INCREMENT,
	cname VARCHAR(20)
);

-- 创建中间表
CREATE TABLE s_c_table(
	sno INT,
	cno INT
);
-- 给sno字段添加外键指向student表的sid主键
ALTER TABLE s_c_table ADD CONSTRAINT fkey01 FOREIGN KEY(sno) REFERENCES student(sid);
-- 给cno字段添加外键指向course表的cid主键
ALTER TABLE s_c_table ADD CONSTRAINT fkey03 FOREIGN KEY(cno) REFERENCES course(cid);

8.3 One-to-one relationship (understanding)

8.3.1 The first one-to-one relationship

We have learned about one-to-many relationships before. In a one-to-many relationship, one row of data in the master table can correspond to multiple rows of data in the slave table, whereas a row of data in the slave table can only correspond to one row of data in the master table. This relationship of one row of data corresponding to one row of data can be regarded as a one-to-one relationship

3.3.2 The second one-to-one relationship

A row of data in table A corresponds to a row of data in table B, and vice versa, a row of data in table B also corresponds to a row of data in table A. At this time, we can use table A as the main table and table B as the slave table, or use B as the main table. The table is regarded as the main table A table is regarded as the slave table

The principle of table creation
Create a foreign key by specifying a field in the slave table and point to the primary key of the master table, and then add a unique constraint to the foreign key field of the slave table

Chapter 9 Multi-Table Association Query

Multi-table association query is to use one SQL statement to query the data of multiple associated tables

9.1 Environment preparation

-- 创建一张分类表(类别id,类别名称.备注:类别id为主键并且自动增长)
CREATE TABLE t_category(
		cid INT PRIMARY KEY auto_increment,
		cname VARCHAR(40)
);
INSERT INTO t_category values(null,'手机数码');
INSERT INTO t_category values(null,'食物');
INSERT INTO t_category values(null,'鞋靴箱包');


-- 创建一张商品表(商品id,商品名称,商品价格,商品数量,类别.备注:商品id为主键并且自动增长)

CREATE TABLE t_product(
		pid INT PRIMARY KEY auto_increment,
		pname VARCHAR(40),
		price DOUBLE,
		num INT,
		cno INT
);

insert into t_product values(null,'苹果电脑',18000,10,1);
insert into t_product values(null,'iPhone8s',5500,100,1);
insert into t_product values(null,'iPhone7',5000,100,1);
insert into t_product values(null,'iPhone6s',4500,1000,1);
insert into t_product values(null,'iPhone6',3800,200,1);
insert into t_product values(null,'iPhone5s',2000,10,1);
insert into t_product values(null,'iPhone4s',18000,1,1);

insert into t_product values(null,'方便面',4.5,1000,2);
insert into t_product values(null,'咖啡',10,100,2);
insert into t_product values(null,'矿泉水',2.5,100,2);

insert into t_product values(null,'法拉利',3000000,50,null);

-- 给 商品表添加外键
ALTER TABLE t_product ADD FOREIGN KEY(cno) REFERENCES t_category(cid);

9.2 Cross query【Understand】

Cross-query is actually the unconditional connection of data in multiple tables for display

9.2.1 Syntax

select a.,a.,b.,b.from a,b ;  

select a.*,b.* from a,b ;  
--或者 
select * from a,b;

9.2.2 Exercises

Use cross lookup categories and items

select * from t_category,t_product;

From the query results, we can see that cross-query is actually a wrong approach. There are a lot of wrong data in the query result set. We call the cross-query result set a Cartesian product.

9.2.3 Cartesian product

Suppose set A={a,b}, set B={0,1,2}, then the Cartesian product of the two sets is {(a,0),(a,1),(a,2),( b,0),(b,1),(b,2)}. Can be extended to the case of multiple collections.

9.3 Inner join query

The result of cross query is not what we want, so how to remove wrong and unwanted records, of course, is through conditional filtering. Usually there is an association relationship between multiple tables to be queried, then the Cartesian product is removed by **association (primary-foreign key relationship)**. This kind of query that removes the Cartesian product by conditional filtering is called a join query. Join query can be divided into inner join query and outer join query. Let's learn inner join query first.

9.3.1 Implicit inner join query

There is no inner join keyword in the implicit inner join query

select [字段,字段,字段] from a,b where 连接条件 (b表里面的外键 = a表里面的主键 ) 

9.3.2 Explicit Inner Join Queries

There is an inner join keyword in the explicit inner join query

select [字段,字段,字段] from a [inner] join b on 连接条件 [ where 其它条件]

9.3.3 Inner join query exercise

Query product information under all categories, if there is no product under this category, it will not be displayed

-- 1 隐式内连接方式 
select *from t_category  c, t_product  p WHERE c.cid = p.cno;

-- 2 显示内连接方式
-- 查询手机数码这个分类下的所有商品的信息以及分类信息
SELECT * FROM t_product tp INNER JOIN t_category tc ON tp.cno = tc.cid WHERE tc.cname = '手机数码';

SELECT * from t_category c INNER JOIN t_product p ON c.cid = p.cno

9.3.4 Features of Inner Join Query

The data in the master table and the slave table can be queried if they meet the connection conditions, and will not be queried if they do not meet the connection conditions

9.4 Outer join query

We found that the inner connection query is the public part that meets the connection conditions. If you want to query all the data in a certain table, you need to use the outer connection query. The outer connection is divided into left outer connection and right outer join

9.4.1 Left outer join query

9.4.1.1 Concept

Use the table on the left of the join as the main table to display all the data in the main table, query and connect the data in the right table according to the conditions, if the conditions are met, it will be displayed, if not, it will be displayed as null. It can be understood as: on the basis of the inner connection, ensure that all the data in the left table is displayed

9.4.1.2 Syntax

select 字段 from a left [outer] join b on 条件

9.4.1.3 Exercises

Query product information under all categories, even if there are no products under this category, the information of this category needs to be displayed

SELECT * FROM t_category c LEFT OUTER JOIN t_product p ON c.cid = p.cno

9.4.2 Right outer join query

9.4.2.1 Concept

Use the table on the right of the join as the main table to display all the data in the table on the right, and query the data in the table on the left of the join according to the conditions. If it is satisfied, it will be displayed, and if it is not satisfied, it will be displayed as null. It can be understood as: on the basis of the inner connection, ensure that all the data in the table on the right is displayed

9.4.2.2 Syntax

select 字段 from a right [outer] join b on 条件

9.4.2.3 Exercises

Query the category information corresponding to all commodities

SELECT * FROM t_category c RIGHT  OUTER JOIN t_product p ON c.cid = p.cno

9.5 union joint query realizes full outer connection query

First of all, it must be clear that joint query is not a way of multi-table join query. Joint query is to combine the query results of multiple query statements into one result and remove duplicate data.

The full outer join query means to query the data of the left table and the right table, and then connect according to the connection conditions

9.5.1 Syntax of union

查询语句1 union 查询语句2 union 查询语句3 ...

9.5.2 Exercises

# 用左外的A union 右外的B
SELECT * FROM t_category c LEFT OUTER JOIN t_product p ON c.cid = p.cno
union
SELECT * FROM t_category c RIGHT  OUTER JOIN t_product p ON c.cid = p.cno

9.6 Self-join query

Self-join query is a special multi-table join query, because the two associated query tables are the same table, virtualized into two tables by taking an alias, and then perform a join query of the two tables

9.6.1 Preparations

-- 员工表
CREATE TABLE emp (
  id INT PRIMARY KEY, -- 员工id
  ename VARCHAR(50), -- 员工姓名
  mgr INT , -- 上级领导
  joindate DATE, -- 入职日期
  salary DECIMAL(7,2) -- 工资
);
-- 添加员工
INSERT INTO emp(id,ename,mgr,joindate,salary) VALUES 
(1001,'孙悟空',1004,'2000-12-17','8000.00'),
(1002,'卢俊义',1006,'2001-02-20','16000.00'),
(1003,'林冲',1006,'2001-02-22','12500.00'),
(1004,'唐僧',1009,'2001-04-02','29750.00'),
(1005,'李逵',1006,'2001-09-28','12500.00'),
(1006,'宋江',1009,'2001-05-01','28500.00'),
(1007,'刘备',1009,'2001-09-01','24500.00'),
(1008,'猪八戒',1004,'2007-04-19','30000.00'),
(1009,'罗贯中',NULL,'2001-11-17','50000.00'),
(1010,'吴用',1006,'2001-09-08','15000.00'),
(1011,'沙僧',1004,'2007-05-23','11000.00'),
(1012,'李逵',1006,'2001-12-03','9500.00'),
(1013,'小白龙',1004,'2001-12-03','30000.00'),
(1014,'关羽',1007,'2002-01-23','13000.00');
#查询孙悟空的上级
SELECT employee.*,manager.ename mgrname FROM emp employee,emp manager where employee.mgr=manager.id AND employee.ename='孙悟空'

9.6.2 Self-join query exercise

Query the employee's number, name, salary and his leader's number, name, salary

#这些数据全部在员工表中
#把t_employee表,即当做员工表,又当做领导表
#领导表是虚拟的概念,我们可以通过取别名的方式虚拟
SELECT employee.id "员工的编号",emp.ename "员工的姓名" ,emp.salary "员工的薪资",
	manager.id "领导的编号" ,manager.ename "领导的姓名",manager.salary "领导的薪资"
FROM emp employee INNER JOIN emp manager
#emp employee:employee.,表示的是员工表的
#emp manager:如果用manager.,表示的是领导表的
ON employee.mgr = manager.id  # 员工的mgr指向上级的id

#表的别名不要加"",给列取别名,可以用"",列的别名不使用""也可以,但是要避免包含空格等特殊符号。

Chapter 10 Subqueries

If a query statement is nested in another query statement, then this query statement is called a subquery, which is divided into: where type, from type, and exists type according to different positions. Note: No matter where the subquery is, the subquery must be enclosed in ().

10.1 where type

① If the subquery is a single-value result (single row and single column), then it can be used (=, > and other comparison operators)

# 查询价格最高的商品信息
select * from t_product where price = (select max(price) from t_product)

②The sub-query is a multi-valued result, so it can be used ([not] in (sub-query result), or >all (sub-query result), or >=all (sub-query result), <all (sub-query result) , <=all(subquery result), or >any(subquery result), or >=any(subquery result), <any(subquery result), <=any(subquery result))

# 查询价格最高的商品信息
SELECT * FROM t_product WHERE price >=ALL(SELECT price FROM t_product)
select * from t_product order by price desc limit 0,1

10.2 from type

The result of a subquery is a result of multiple rows and multiple columns, similar to a table.

You must alias the subquery, that is, the name of the temporary table, and do not add "" and spaces to the alias of the table.

-- 思路一: 使用连接查询
-- 使用外连接,查询出分类表的所有数据
SELECT tc.cname,COUNT(tp.pid) FROM t_category tc LEFT JOIN t_product tp ON tp.cno = tc.cid GROUP BY tc.cname

-- 思路二: 使用子查询
-- 第一步:对t_product根据cno进行分组查询,统计每个分类的商品数量
SELECT cno,COUNT(pid) FROM t_product GROUP BY cno
-- 第二步: 用t_category表去连接第一步查询出来的结果,进行连接查询,此时要求查询出所有的分类
SELECT tc.cname,IFNULL(tn.total,0) '总数量' FROM t_category tc LEFT JOIN (SELECT cno,COUNT(pid) total FROM t_product GROUP BY cno) tn ON tn.cno=tc.cid

10.3 exists型

# 查询那些有商品的分类
SELECT cid,cname FROM t_category tc WHERE EXISTS (SELECT * FROM t_product tp WHERE tp.cno = tc.cid);

Guess you like

Origin blog.csdn.net/qq_42076902/article/details/121701974