MySQL Basic Knowledge Notes 2--[Basic Grammar]

Today's content

  1. DQL: query statement

    1. Sort query
    2. Aggregate function
    3. Group query
    4. Paging query
  2. constraint

  3. Relationship between multiple tables

  4. Paradigm

  5. Database backup and restore

DQL: query statement

Sort query

Syntax: order by clause

  • order by sorting field 1 sorting method 1, sorting field 2 sorting method 2...

Sort by:

  • ASC: Ascending order, the default.
  • DESC: descending order.

note:

If there are multiple sorting conditions, the second condition will be judged when the condition value of the current side is the same.

Aggregate function: Take a column of data as a whole and perform vertical calculations.

count: count the number

  1. Generally select non-empty columns: primary key
  2. count(*)

max: calculate the maximum value

min: calculate the minimum value

sum: calculate the sum

avg: calculate the average

Note: The calculation of aggregate functions excludes null values.
solution:

  1. Choose not to include non-empty columns for calculation
    2. IFNULL function

Group query:

Syntax: group by group field;

note:

  1. Fields to be queried after grouping: grouping fields, aggregate functions
  2. The difference between where and having?
    1. Where is defined before grouping, if the conditions are not met, it will not participate in grouping. Having limited after grouping, if the result is not satisfied, it will not be queried
    2. Aggregate functions cannot be followed after where, and having aggregate functions can be judged.
-- 按照性别分组。分别查询男、女同学的平均分

SELECT sex , AVG(math) FROM student GROUP BY sex;

-- 按照性别分组。分别查询男、女同学的平均分,人数

SELECT sex , AVG(math),COUNT(id) FROM student GROUP BY sex;

--  按照性别分组。分别查询男、女同学的平均分,人数 要求:分数低于70分的人,不参与分组
SELECT sex , AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex;

--  按照性别分组。分别查询男、女同学的平均分,人数 要求:分数低于70分的人,不参与分组,分组之后。人数要大于2个人
SELECT sex , AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex HAVING COUNT(id) > 2;
SELECT sex , AVG(math),COUNT(id) 人数 FROM student WHERE math > 70 GROUP BY sex HAVING 人数 > 2;

Paging query

grammar

Index starting from limit, the number of queries per page;

official

Starting index = (current page number-1) * the number of items displayed per page

-- 每页显示3条记录 
SELECT * FROM student LIMIT 0,3; -- 第1页
SELECT * FROM student LIMIT 3,3; -- 第2页
SELECT * FROM student LIMIT 6,3; -- 第3页

limit is a MySQL "dialect", unique to MySQL

constraint

concept

Limit the data in the table to ensure the correctness, validity and completeness of the data.

classification

  1. Primary key constraint: primary key
  2. Non-empty constraint: not null
  3. The only constraint: unique
  4. Foreign key constraint: foreign key

Non-null constraint: not null, the value of a column cannot be null

  1. Add constraints when creating a table
    CREATE TABLE stu(
    id INT,
    NAME VARCHAR(20) NOT NULL – name is not empty
    );

  2. After creating the table, add a non-empty constraint
    ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;

  3. Delete the non-empty constraint of name
    ALTER TABLE stu MODIFY NAME VARCHAR(20);

The only constraint:

unique, the value of a column cannot be repeated

note:

  • The unique constraint can have a NULL value, but only one record can be null, and the value of the column limited by the unique constraint can have multiple nulls

When creating a table, add a unique constraint

CREATE TABLE stu(
	id INT,
	phone_number VARCHAR(20) UNIQUE -- 手机号
);

Delete unique constraint

ALTER TABLE stu DROP INDEX phone_number;

After the table is created, add a unique constraint

ALTER TABLE stu MODIFY phone_number VARCHAR(20) UNIQUE;

Primary key constraint: primary key

note

  1. Meaning: non-empty and unique
  2. A table can only have one field as the primary key
  3. The primary key is the unique identification of the records in the table

When creating a table, add a primary key constraint

create table stu(
	id int primary key,-- 给id添加主键约束
	name varchar(20)
);

Delete primary key

-- 错误 alter table stu modify id int ;
ALTER TABLE stu DROP PRIMARY KEY;

After creating the table, add the primary key

ALTER TABLE stu MODIFY id INT PRIMARY KEY;

Automatic growth

Concept: If a column is of numeric type, use auto_increment to complete the value of automatic growth

When creating a table, add primary key constraints and complete primary key self-growth

create table stu(
id int primary key auto_increment,-- 给id添加主键约束
name varchar(20)
);--自动增长的值只跟上一条记录有关系

Delete automatic growth

ALTER TABLE stu MODIFY id INT;

Add automatic growth

ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;

Foreign key constraint: foreign key

Let the table and the table have a relationship to ensure the correctness of the data.

When creating a table, you can add foreign keys

grammar:

create table 表名(
	....
	外键列
	constraint 外键名称 foreign key (外键列名称) references 主表名称(主表列名称)
);

Delete foreign key

ALTER TABLE 表名 DROP FOREIGN KEY 外键名称;

After creating the table, add the foreign key

ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称);

Cascade operation

  1. Add cascade operation

    语法:
    ALTER TABLE 表名 ADD CONSTRAINT 外键名称 
    FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称) ON UPDATE CASCADE ON DELETE CASCADE  ;
    
  2. classification:

    1. Cascade update:ON UPDATE CASCADE
    2. Cascade delete:ON DELETE CASCADE

Database design

Relationship between multiple tables

classification:

One-to-one (understanding):

  • Such as: person and ID card
  • Analysis: A person has only one ID, and one ID can only correspond to one person

One to many (many to one):

  • Such as: departments and employees
  • Analysis: There are multiple employees in a department, and an employee can only correspond to one department

Many to many:

  • Such as: students and courses
  • Analysis: One student can choose many courses, and one course can be chosen by many students

Realization relationship:

One to many (many to one):

  • Such as: departments and employees
  • Realization: create a foreign key on the more side, and point to the primary key on the one side.

Many to many:

  • Such as: students and courses
  • Realization method: The realization of many-to-many relationship requires the aid of the third intermediate table. The intermediate table contains at least two fields, these two fields are used as the foreign key of the third table, pointing to the primary keys of the two tables respectively

One-to-one (understanding):

  • Such as: person and ID card
  • Implementation: One-to-one relationship is achieved, and a unique foreign key can be added on either side to point to the primary key of the other side.

Case

-- 创建旅游线路分类表 tab_category
-- cid 旅游线路分类主键,自动增长
-- cname 旅游线路分类名称非空,唯一,字符串 100
CREATE TABLE tab_category (
	cid INT PRIMARY KEY AUTO_INCREMENT,
	cname VARCHAR(100) NOT NULL UNIQUE
);

-- 创建旅游线路表 tab_route
/*
rid 旅游线路主键,自动增长
rname 旅游线路名称非空,唯一,字符串 100
price 价格
rdate 上架时间,日期类型
cid 外键,所属分类
*/
CREATE TABLE tab_route(
	rid INT PRIMARY KEY AUTO_INCREMENT,
	rname VARCHAR(100) NOT NULL UNIQUE,
	price DOUBLE,
	rdate DATE,
	cid INT,
	FOREIGN KEY (cid) REFERENCES tab_category(cid)
);

/*创建用户表 tab_user
uid 用户主键,自增长
username 用户名长度 100,唯一,非空
password 密码长度 30,非空
name 真实姓名长度 100
birthday 生日
sex 性别,定长字符串 1
telephone 手机号,字符串 11
email 邮箱,字符串长度 100
*/
CREATE TABLE tab_user (
	uid INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(100) UNIQUE NOT NULL,
	PASSWORD VARCHAR(30) NOT NULL,
	NAME VARCHAR(100),
	birthday DATE,
	sex CHAR(1) DEFAULT '男',
	telephone VARCHAR(11),
	email VARCHAR(100)
);

/*
创建收藏表 tab_favorite
rid 旅游线路 id,外键
date 收藏时间
uid 用户 id,外键
rid 和 uid 不能重复,设置复合主键,同一个用户不能收藏同一个线路两次
*/
CREATE TABLE tab_favorite (
	rid INT, -- 线路id
	DATE DATETIME,
	uid INT, -- 用户id
	-- 创建复合主键
	PRIMARY KEY(rid,uid), -- 联合主键
	FOREIGN KEY (rid) REFERENCES tab_route(rid),
	FOREIGN KEY(uid) REFERENCES tab_user(uid)
);

The paradigm of database design

concept

When designing a database, some specifications need to be followed. To follow the requirements of the latter paradigm, you must first follow all the requirements of the previous paradigm. When
designing a relational database, follow different specifications and design a reasonable relational database. These different specifications are called different paradigms and various paradigms. Sub-specification, the higher the paradigm, the lower the redundancy of the database.
​Currently there are six paradigms for relational databases: First Normal Form (1NF), Second Normal Form (2NF), Third Normal Form (3NF), Bath-Cord Normal Form (BCNF), Fourth Normal Form (4NF) and Fifth Normal Form (5NF, also known as the perfect paradigm).

classification

First Normal Form (1NF): Each column is an indivisible atomic data item

Second Normal Form (2NF): On the basis of 1NF, non-code attributes must be completely dependent on the code (on the basis of 1NF, partial functional dependence of non-primary attributes on the main code is eliminated)

  1. Function dependency: A->B, if the value of the A attribute (attribute group) is used, the value of the unique B attribute can be determined. It is said that B depends on A,
    for example: student ID -> name. (Student number, course name) --> score

  2. Full functional dependency: A->B. If A is an attribute group, the determination of the attribute value of B needs to depend on all attribute values ​​in the attribute group A.
    For example: (student ID, course name) --> score

  3. Partial functional dependence: A–>B. If A is an attribute group, the determination of the attribute value of B only needs to depend on some values ​​in the attribute group A.
    For example: (student ID, course name) -> name

  4. The transfer function depends on: A–>B, B – >C. If the value of the A attribute (attribute group) is used, the value of the unique B attribute can be determined, and the value of the only C attribute can be determined by the value of the B attribute (attribute group) , It is said that the transfer function of C depends on A.
    For example: student number -> department name, department name -> department head

  5. Code: If an attribute or attribute group is completely dependent on all other attributes in a table, then this attribute (attribute group) is called the code of the table.
    For example: the code in the table is: (student ID, course name)

    • Primary attribute: all attributes in the code attribute group

    • Non-primary attributes: the attributes of the coded attribute group

Third Normal Form (3NF): On the basis of 2NF, any non-primary attribute does not depend on other non-primary attributes (eliminating transitive dependence on the basis of 2NF)

Database backup and restore

Command Line:

Backup:

mysqldump -u username -p password database name> saved path

reduction:

  1. Log in to the database
  2. Create database
  3. Use database
  4. executable file. source file path.

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/109084442