Encyclopedia of SQL statements (detailed explanation)

SQL

foreword

insert image description here
  This tutorial is a summary of commonly used SQL statements. I put it on Code Cloud. Project address: https://gitee.com/love-code-bear/java/blob/master/SQL.md


1 DDL

1.1 Show included databases

SHOW DATABASES;

1.2 Create a database

CREATE DATABASE db2;
CREATE DATABASE IF NOT EXISTS db2;

1.3 Delete the database

DROP DATABASE db2;
drop DATABASE IF EXISTS db2;

– View the currently used database

SELECT DATABASE();

1.4 Using the database

use db1;

1.4.1 Create table

CREATE TABLE jd_user(
id int,
username VARCHAR(32),
password VARCHAR(32)
);

1.4.2 View the structure of the table

DESC stu;

1.4.3 View all tables under the current database

USE DATABASE db1;
SHOW TABLES;

1.4.4 Basic CRUD

1.4.4.1 Delete table

DROP TABLE tb_user;
DROP TABLE IF EXISTS tb_user;

1.4.4.2 Add column

ALTER TABLE jd_user ADD address VARCHAR(32);

1.4.4.3 Modify the table name

ALTER TABLE jd_user RENAME TO jd_user;

1.4.4.4 Modify data type

ALTER TABLE jd_user MODIFY address CHAR(32);
DESC jd_user;

1.4.4.5 Modify column names and data types

ALTER TABLE jd_user CHANGE address location VARCHAR(64);

1.4.5 Query all data

SELECT * FROM jd_user;
SELECT * FROM stu;

2 DML

2.1 Add data to the specified column

2.1.1 Modify the encoding format of the Chinese column (modify the column name and data type):

alter table stu change name name varchar(255) character set utf8;
INSERT INTO stu(id,name) VALUES(1,'张三');

2.1.2 Add data to all columns

alter table stu change sex sex varchar(255) character set utf8;
INSERT INTO stu(id,name,sex,birthday,score,email,tel,status) VALUES
(2,'lisa','女','1999-11-11',98.00,'[email protected]',1123,1);

2.1.3 Add data to all columns, the list of column names can be omitted

INSERT INTO stu VALUES(3,'小米','男','1998-10-17',93.00,'[email protected]',1433,1);

2.1.4 Batch Add

INSERT INTO stu VALUES
(4,'huawei','男','1998-10-17',93.00,'[email protected]',1433,1),
(5,'荣耀','男','1998-10-17',93.00,'[email protected]',1433,1),
(6,'苹果','男','1998-10-17',93.00,'[email protected]',1433,1);

2.2 Modify data

2.2.1 Change Zhang San's gender to male

UPDATE stu SET sex = '男' WHERE name = '张三';

2.2.2 Change Zhang San's birthday to 2000-02-28, and his score to 99.00

UPDATE stu SET birthday = '2000-02-28',score = '99.00' WHERE name = '张三';

2.2.3 If the update statement has no where condition, all the data in the table will be modified

2.3 Delete data

2.3.1 Delete Xiaomi records

DELETE FROM stu WHERE name = '小米';

2.4 Simply create tables, add data, and query data

– USE DATABASE
USE db1;
– CREATE TABLE

CREATE TABLE stu1 (
id int,
name VARCHAR(32),
age int,
sex VARCHAR(4),
address VARCHAR(64),
math DOUBLE(5,2),
english DOUBLE(5,2),
hire_date DATE
);

– insert data

ALTER TABLE stu1 CHANGE name name VARCHAR(32) character set utf8;
ALTER TABLE stu1 CHANGE sex sex VARCHAR(4) character set utf8;
ALTER TABLE stu1 CHANGE address address VARCHAR(64) character set utf8;
INSERT INTO stu1(id,name,age,sex,address,math,english,hire_date) 
VALUES
(1,'张一',25,'男','杭州',66.00,78.00,'1998-09-09'),
(2,'张二',24,'女','北京',87.00,76.00,'1996-09-09'),
(3,'张三',22,'男','郑州',94.00,65.00,'1997-09-09'),
(4,'张四',23,'男','合肥',69.00,75.00,'1998-09-09'),
(5,'张五',23,'女','无锡',76.00,79.00,'1999-09-09'),
(6,'张六',24,'女','苏州',88.00,94.00,'1998-03-09'),
(7,'张七',21,'男','南通',89.00,90.00,'1998-05-09'),
(8,'张八',22,'男','南充',98.00,90.00,'1998-07-09');

– Query all data

SELECT * FROM stu1;
USE db1;

3 DQL

3.1 Basic query

3.1.1 To query the data of all columns, the list of column names can be replaced by *

SELECT *FROM stu1;
SELECT `name`,age,sex,address,math,english,hire_date FROM stu1;

3.1.2 Query name age two columns

SELECT `name`,age FROM stu1;

3.1.3 Query English scores

SELECT english FROM stu1;

3.1.4 Remove duplicate records

SELECT DISTINCT english FROM stu1;

3.1.5 Alias ​​when querying as

SELECT name AS 姓名,math AS 数学,english AS 英语 FROM stu1;

3.2 Condition query

3.2.1 Query the information of students over the age of 23

SELECT * FROM stu1	WHERE age > 23;

3.2.2 Query the information of students whose age is >=24 years old

SELECT * FROM stu1 WHERE age >= 24;

3.2.3 Query the information of students aged 21<=age<=23

SELECT * FROM stu1 WHERE age>=21 AND age <= 23;
SELECT * FROM stu1 WHERE age BETWEEN 21 AND 23;

3.2.4 Query the information of students whose enrollment time is between 1997-05-09–1998-07-09

SELECT * FROM stu1 WHERE hire_date BETWEEN '1997-05-09' AND '1998-07-09';

3.2.5 Query information of students whose age is equal to 21

SELECT * FROM stu1 WHERE age = 21;

3.2.6 Query the information of students whose age is equal to 21 years old or 24 years old or 25 years old

SELECT * FROM stu1 WHERE age = 21 OR age = 24 OR age = 25;
SELECT * FROM stu1 WHERE age IN(21,24,25);

3.2.7 Query the student information whose English score is null

SELECT * FROM stu1 WHERE english IS NOT null;

3.3 Fuzzy query

3.3.1 Query the student information with the surname 'Zhang'

SELECT * FROM stu1 WHERE `name` LIKE '张%';
-- 查询第二个字是'三'的学员信息
SELECT * FROM stu1 WHERE `name` LIKE '_三%';
-- 查询名字中含有'四'的学员信息
SELECT * FROM stu1 WHERE `name` LIKE '%四%';

3.4 Sorting queries

3.4.1 Query student information, sorted in ascending order of age

SELECT * FROM stu1 ORDER BY age ASC;

3.4.2 Query student information, sort in descending order of math scores

SELECT * FROM stu1 ORDER BY math DESC;

3.4.3 Query student information, arrange in descending order of English scores, if the English scores are the same, then sort in ascending order of math scores

SELECT * FROM stu1 ORDER BY english DESC , math ASC;

3.5 Group query

3.5.1 Aggregate functions

3.5.1.1 Count the number of students in the class

SELECT COUNT(id) FROM stu1;
SELECT COUNT(*) FROM stu1;

3.5.1.2 Query the highest math score

SELECT MAX(math) FROM stu1;

3.5.1.3 Query the minimum math score

SELECT MIN(math) FROM stu1;

3.5.1.4 Query the total score of math scores

SELECT SUM(math) FROM stu1;

3.5.1.5 Query the average score of math scores

SELECT AVG(math) FROM stu1;

3.5.2 Grouping functions

3.5.2.1 Query the average scores of male and female students

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

3.5.2.2 Query the average scores of male students and female students, as well as their respective numbers

SELECT sex,AVG(math),COUNT(*) FROM stu1 GROUP BY sex;

3.5.2.3 Query the average scores of male students and female students, as well as their respective numbers, and require those whose scores are lower than 80 not to participate in the group

SELECT sex,AVG(math),COUNT(*) FROM stu1 WHERE math > 80 GROUP BY sex;

3.5.2.4 Query the respective average scores of male and female students, as well as their respective numbers. Those whose scores are lower than 80 are not required to participate in the group, and the number of people after grouping is greater than 2

SELECT sex,AVG(math),COUNT(*) FROM stu1 WHERE math > 80 GROUP BY sex HAVING COUNT(*) > 2;

3.6 Pagination query

SELECT * FROM  stu1;

3.6.1 Start query from 0, query the first page of data

SELECT  * FROM stu1 LIMIT 0,3;

3.62 Display 3 pieces of data per page and display the first page

SELECT  * FROM stu1 LIMIT 0,3;

3.6.3 Display 3 pieces of data per page and display the second page

SELECT  * FROM stu1 LIMIT 3,3;

3.6.4 Display 3 pieces of data per page and display the third page

SELECT  * FROM stu1 LIMIT 6,3;

3.6.5 Display 4 pieces of data per page and display the second page

SELECT  * FROM stu1 LIMIT 4,4;

3.7 Constraints

3.7.1 Field constraints

-- 员工表
CREATE TABLE emp(
id INT PRIMARY KEY,/*员工id主键,且自增长*/
ename VARCHAR(32) UNIQUE,/*员工姓名,非空且唯一*/
joindate DATE NOT NULL,/*入职日期非空*/
salary DOUBLE(7,2) NOT NULL,/*薪水,非空*/
bonus DOUBLE(7,2) DEFAULT 0/*奖金,默认为0*/
);
DESC emp;
ALTER TABLE emp CHANGE ename ename VARCHAR(32) CHARACTER set utf8;
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(1,'张三','1999-11-11',8800,5000);
SELECT * FROM emp;

3.7.2 Demonstrate primary key constraints, non-null and unique

INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(NULL,'张三','1999-11-11',8800,5000);
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(1,'张三','1999-11-11',8800,5000);
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(2,'李四','1999-11-11',8800,5000);

3.7.3 Demonstrating not-null constraints

DELETE FROM emp WHERE id = 3;
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(3,null,'1999-11-11',8800,5000);

3.7.4 Demonstrating unique constraints

INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(3,'李四','1999-11-11',8800,5000);

3.7.5 Operations on constraints

3.7.5.1 Deleting Constraints

ALTER TABLE emp MODIFY ename VARCHAR(32) CHARACTER set utf8;

3.7.5.2 Add constraints

ALTER TABLE emp MODIFY ename VARCHAR(32) NOT NULL ;
DESC emp;
DROP TABLE emp;

3.7.5.3 Foreign key constraints (example demonstration)

-- 员工表
CREATE TABLE emp(
id INT PRIMARY KEY auto_increment,/*员工id主键,且自增长*/
name VARCHAR(32),/*员工姓名,非空且唯一*/
age INT,
dep_id INT,/*联系到拎一个表*/
-- 添加一个外键约束
CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id)
);
-- 部门表
CREATE TABLE dept(
id INT PRIMARY KEY auto_increment,
dep_name VARCHAR(32),
address VARCHAR(32)
);
DESC emp;
DESC dept;
DROP TABLE emp;
DROP TABLE dept;
ALTER TABLE emp CHANGE name name VARCHAR(32) CHARACTER set utf8;
ALTER TABLE dept CHANGE dep_name dep_name VARCHAR(32) CHARACTER set utf8;
ALTER TABLE dept CHANGE address address VARCHAR(32) CHARACTER set utf8;
INSERT INTO emp (name,age,dep_id) VALUES
('张三',20,1),
('李四',20,1),
('王五',20,1),
('赵六',20,2),
('孙七',22,2),
('周八',18,2);
INSERT INTO dept (dep_name,address) VALUES
('研发部','广州'),
('销售部','深圳');
SELECT * FROM emp;
SELECT * FROM dept;
-- 删除外键
ALTER TABLE emp DROP FOREIGN KEY fk_emp_dept;
-- 添加外键
ALTER TABLE emp ADD CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id);

4 foreign keys

Using the database, display all tables

USE db1;
SHOW TABLES;

4.1 Establishment of foreign keys

4.1.1 Many-to-many relationship

-- 订单表
CREATE TABLE tb_order(
id INT PRIMARY KEY auto_increment,
payment double(10,2),
payment_type TINYINT,
status TINYINT
);
-- 商品表
CREATE TABLE tb_goods(
id INT PRIMARY KEY auto_increment,
title VARCHAR(100),
price DOUBLE(10,2)
);
-- 中间表
CREATE TABLE tb_order_goods(
id INT PRIMARY KEY auto_increment,
order_id INT,
goods_id INT
);
-- 添加外键
ALTER TABLE tb_order_goods ADD CONSTRAINT fk_order_id FOREIGN KEY(order_id) REFERENCES tb_order(id);
ALTER TABLE tb_order_goods ADD CONSTRAINT fk_goods_id FOREIGN KEY(goods_id) REFERENCES tb_goods(id);
SHOW TABLES;

4.1.2 One-to-one relationship

-- 用户表
CREATE TABLE tb_user(
id INT PRIMARY KEY auto_increment,
photo VARCHAR(100),
name VARCHAR(32),
age INT,
sex VARCHAR(4),
desc_id INT UNIQUE,
CONSTRAINT tb_user_desc FOREIGN KEY(desc_id) REFERENCES tb_user_desc(id) 
);
-- 用户详情表
CREATE TABLE tb_user_desc(
id INT PRIMARY KEY auto_increment,
city VARCHAR(32),
edu VARCHAR(32),
income DOUBLE(7,2),
status TINYINT
);
ALTER TABLE tb_user_desc CHANGE status status VARCHAR(16) CHARACTER set utf8;
INSERT into tb_user_desc(city,edu,income,status) VALUES
('广州','本科',3000,'单身'),
('广州','硕士',12000,'单身');
INSERT into tb_user(photo,`name`,age,sex,desc_id) VALUES
('c盘','林青霞',22,'女',1),
('d盘','风清扬',24,'男',2);
ALTER TABLE tb_user auto_increment = 1;
SELECT * FROM tb_user;
SELECT * FROM tb_user_desc;
DESC tb_user;
DESC tb_user_desc;
DROP TABLE tb_user;

4.1.3 View all foreign keys

SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE;

4.2 Example Demonstration Exercise

-- 音乐专辑表名
CREATE TABLE music(
title VARCHAR(32),/*专辑名*/
alias VARCHAR(32),/*专辑别名*/
image VARCHAR(64),/*封面图片*/
style VARCHAR(16),/*流派(经典、流行、民谣)*/
type VARCHAR(8),/*类型(专辑,单曲)*/
medium VARCHAR(8),/*介质(胶片,cd)*/
publish_time DATE,/*发行时间*/
publisher VARCHAR(8),/*出版者*/
number TINYINT,/*唱片数量*/
barcode BIGINT,/*条形码*/
summary VARCHAR(1024),/*简介*/
artist VARCHAR(32),/*艺术家*/
id INT UNIQUE/*编号,唯一*/
);
-- 曲目表名
CREATE TABLE song(
name VARCHAR(32),/*歌曲名*/
serial_number TINYINT,/*歌曲序号*/
id INT UNIQUE/*编号,唯一*/
);
-- 评论表名
CREATE TABLE review(
content VARCHAR(1024),/*评论内容*/
rating TINYINT,/*评分1-5*/
review datetime,/*评论时间*/
content_user_id INT,
content_music_id INT
);
-- 用户表名
CREATE TABLE user(
username VARCHAR(32),
image VARCHAR(64),
signture VARCHAR(64),
name VARCHAR(32),
id INT PRIMARY KEY
);
-- 展示
DESC music;
DESC song;
DESC review;
DESC user;
-- 删除
DROP TABLE music;
DROP TABLE song;
DROP TABLE review;
DROP TABLE user;
-- 专辑和用户的中间表
CREATE TABLE music_user(
id INT PRIMARY KEY auto_increment,
music_id INT,
user_id INT
);
-- 添加专辑和用户外键
ALTER TABLE music_user ADD CONSTRAINT fk_music_id FOREIGN KEY(music_id) REFERENCES music(id);
ALTER TABLE music_user ADD CONSTRAINT fk_user_id FOREIGN KEY(user_id) REFERENCES user(id);
-- 添加短评和用户外键
ALTER TABLE review ADD CONSTRAINT fk_review_user FOREIGN KEY(content_user_id) REFERENCES user(id);
-- 添加短评专辑外键
ALTER TABLE review ADD CONSTRAINT fk_review_music FOREIGN KEY(content_music_id) REFERENCES music(id);
-- 添加曲目和专辑外键
ALTER TABLE song ADD CONSTRAINT fk_song_music FOREIGN KEY(id) REFERENCES music(id);
ALTER TABLE song DROP FOREIGN KEY fk_song_user;

reverse model

– Multi-table query

SELECT * FROM emp;
SELECT * FROM dept;
SELECT * FROM emp,dept;

– Generate Cartesian product (there are two sets of ab, remove all combinations of a and b)
– Eliminate invalid data
– Query the data of emp and dept, emp.dep_id = dept.id
– Implicit inner join

SELECT * FROM emp,dept WHERE emp.dep_id = dept.id;

– Query the name and age of emp and the dep_name of the dept table

SELECT emp.`name`,emp.age,dept.dep_name FROM emp,dept WHERE emp.dep_id = dept.id;

– Alias ​​the table

SELECT t1.`name`,t1.age,t2.dep_name FROM emp AS t1,dept AS t2 WHERE t1.dep_id = t2.id;

– explicit inner join

SELECT * FROM emp LEFT OUTER JOIN dept ON emp.dep_id = dept.id;
SELECT * FROM emp LEFT /*OUTER*/ JOIN dept ON emp.dep_id = dept.id;

– right outer join

SELECT * FROM emp RIGHT OUTER JOIN dept ON emp.dep_id = dept.id;
SELECT * FROM emp RIGHT /*OUTER*/ JOIN dept ON emp.dep_id = dept.id;
```# 1 DDL

## 1.1  显示所包含的数据库

```mysql
SHOW DATABASES;

1.2 Create a database

CREATE DATABASE db2;
CREATE DATABASE IF NOT EXISTS db2;

1.3 Delete the database

DROP DATABASE db2;
drop DATABASE IF EXISTS db2;

– View the currently used database

SELECT DATABASE();

1.4 Using the database

use db1;

1.4.1 Create table

CREATE TABLE jd_user(
id int,
username VARCHAR(32),
password VARCHAR(32)
);

1.4.2 View the structure of the table

DESC stu;

1.4.3 View all tables under the current database

USE DATABASE db1;
SHOW TABLES;

1.4.4 Basic CRUD

1.4.4.1 Delete table

DROP TABLE tb_user;
DROP TABLE IF EXISTS tb_user;

1.4.4.2 Add column

ALTER TABLE jd_user ADD address VARCHAR(32);

1.4.4.3 Modify the table name

ALTER TABLE jd_user RENAME TO jd_user;

1.4.4.4 Modify data type

ALTER TABLE jd_user MODIFY address CHAR(32);
DESC jd_user;

1.4.4.5 Modify column names and data types

ALTER TABLE jd_user CHANGE address location VARCHAR(64);

1.4.5 Query all data

SELECT * FROM jd_user;
SELECT * FROM stu;

2 DML

2.1 Add data to the specified column

2.1.1 Modify the encoding format of the Chinese column (modify the column name and data type):

alter table stu change name name varchar(255) character set utf8;
INSERT INTO stu(id,name) VALUES(1,'张三');

2.1.2 Add data to all columns

alter table stu change sex sex varchar(255) character set utf8;
INSERT INTO stu(id,name,sex,birthday,score,email,tel,status) VALUES
(2,'lisa','女','1999-11-11',98.00,'[email protected]',1123,1);

2.1.3 Add data to all columns, the list of column names can be omitted

INSERT INTO stu VALUES(3,'小米','男','1998-10-17',93.00,'[email protected]',1433,1);

2.1.4 Batch Add

INSERT INTO stu VALUES
(4,'huawei','男','1998-10-17',93.00,'[email protected]',1433,1),
(5,'荣耀','男','1998-10-17',93.00,'[email protected]',1433,1),
(6,'苹果','男','1998-10-17',93.00,'[email protected]',1433,1);

2.2 Modify data

2.2.1 Change Zhang San's gender to male

UPDATE stu SET sex = '男' WHERE name = '张三';

2.2.2 Change Zhang San's birthday to 2000-02-28, and his score to 99.00

UPDATE stu SET birthday = '2000-02-28',score = '99.00' WHERE name = '张三';

2.2.3 If the update statement has no where condition, all the data in the table will be modified

2.3 Delete data

2.3.1 Delete Xiaomi records

DELETE FROM stu WHERE name = '小米';

2.4 Simply create tables, add data, and query data

– USE DATABASE
USE db1;
– CREATE TABLE

CREATE TABLE stu1 (
id int,
name VARCHAR(32),
age int,
sex VARCHAR(4),
address VARCHAR(64),
math DOUBLE(5,2),
english DOUBLE(5,2),
hire_date DATE
);

– insert data

ALTER TABLE stu1 CHANGE name name VARCHAR(32) character set utf8;
ALTER TABLE stu1 CHANGE sex sex VARCHAR(4) character set utf8;
ALTER TABLE stu1 CHANGE address address VARCHAR(64) character set utf8;
INSERT INTO stu1(id,name,age,sex,address,math,english,hire_date) 
VALUES
(1,'张一',25,'男','杭州',66.00,78.00,'1998-09-09'),
(2,'张二',24,'女','北京',87.00,76.00,'1996-09-09'),
(3,'张三',22,'男','郑州',94.00,65.00,'1997-09-09'),
(4,'张四',23,'男','合肥',69.00,75.00,'1998-09-09'),
(5,'张五',23,'女','无锡',76.00,79.00,'1999-09-09'),
(6,'张六',24,'女','苏州',88.00,94.00,'1998-03-09'),
(7,'张七',21,'男','南通',89.00,90.00,'1998-05-09'),
(8,'张八',22,'男','南充',98.00,90.00,'1998-07-09');

– Query all data

SELECT * FROM stu1;
USE db1;

3 DQL

3.1 Basic query

3.1.1 To query the data of all columns, the list of column names can be replaced by *

SELECT *FROM stu1;
SELECT `name`,age,sex,address,math,english,hire_date FROM stu1;

3.1.2 Query name age two columns

SELECT `name`,age FROM stu1;

3.1.3 Query English scores

SELECT english FROM stu1;

3.1.4 Remove duplicate records

SELECT DISTINCT english FROM stu1;

3.1.5 Alias ​​when querying as

SELECT name AS 姓名,math AS 数学,english AS 英语 FROM stu1;

3.2 Condition query

3.2.1 Query the information of students over the age of 23

SELECT * FROM stu1	WHERE age > 23;

3.2.2 Query the information of students whose age is >=24 years old

SELECT * FROM stu1 WHERE age >= 24;

3.2.3 Query the information of students aged 21<=age<=23

SELECT * FROM stu1 WHERE age>=21 AND age <= 23;
SELECT * FROM stu1 WHERE age BETWEEN 21 AND 23;

3.2.4 Query the information of students whose enrollment time is between 1997-05-09–1998-07-09

SELECT * FROM stu1 WHERE hire_date BETWEEN '1997-05-09' AND '1998-07-09';

3.2.5 Query information of students whose age is equal to 21

SELECT * FROM stu1 WHERE age = 21;

3.2.6 Query the information of students whose age is equal to 21 years old or 24 years old or 25 years old

SELECT * FROM stu1 WHERE age = 21 OR age = 24 OR age = 25;
SELECT * FROM stu1 WHERE age IN(21,24,25);

3.2.7 Query the student information whose English score is null

SELECT * FROM stu1 WHERE english IS NOT null;

3.3 Fuzzy query

3.3.1 Query the student information with the surname 'Zhang'

SELECT * FROM stu1 WHERE `name` LIKE '张%';
-- 查询第二个字是'三'的学员信息
SELECT * FROM stu1 WHERE `name` LIKE '_三%';
-- 查询名字中含有'四'的学员信息
SELECT * FROM stu1 WHERE `name` LIKE '%四%';

3.4 Sorting queries

3.4.1 Query student information, sorted in ascending order of age

SELECT * FROM stu1 ORDER BY age ASC;

3.4.2 Query student information, sort in descending order of math scores

SELECT * FROM stu1 ORDER BY math DESC;

3.4.3 Query student information, arrange in descending order of English scores, if the English scores are the same, then sort in ascending order of math scores

SELECT * FROM stu1 ORDER BY english DESC , math ASC;

3.5 Group query

3.5.1 Aggregate functions

3.5.1.1 Count the number of students in the class

SELECT COUNT(id) FROM stu1;
SELECT COUNT(*) FROM stu1;

3.5.1.2 Query the highest math score

SELECT MAX(math) FROM stu1;

3.5.1.3 Query the minimum math score

SELECT MIN(math) FROM stu1;

3.5.1.4 Query the total score of math scores

SELECT SUM(math) FROM stu1;

3.5.1.5 Query the average score of math scores

SELECT AVG(math) FROM stu1;

3.5.2 Grouping functions

3.5.2.1 Query the average scores of male and female students

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

3.5.2.2 Query the average scores of male students and female students, as well as their respective numbers

SELECT sex,AVG(math),COUNT(*) FROM stu1 GROUP BY sex;

3.5.2.3 Query the average scores of male students and female students, as well as their respective numbers, and require those whose scores are lower than 80 not to participate in the group

SELECT sex,AVG(math),COUNT(*) FROM stu1 WHERE math > 80 GROUP BY sex;

3.5.2.4 Query the respective average scores of male and female students, as well as their respective numbers. Those whose scores are lower than 80 are not required to participate in the group, and the number of people after grouping is greater than 2

SELECT sex,AVG(math),COUNT(*) FROM stu1 WHERE math > 80 GROUP BY sex HAVING COUNT(*) > 2;

3.6 Pagination query

SELECT * FROM  stu1;

3.6.1 Start query from 0, query the first page of data

SELECT  * FROM stu1 LIMIT 0,3;

3.62 Display 3 pieces of data per page and display the first page

SELECT  * FROM stu1 LIMIT 0,3;

3.6.3 Display 3 pieces of data per page and display the second page

SELECT  * FROM stu1 LIMIT 3,3;

3.6.4 Display 3 pieces of data per page and display the third page

SELECT  * FROM stu1 LIMIT 6,3;

3.6.5 Display 4 pieces of data per page and display the second page

SELECT  * FROM stu1 LIMIT 4,4;

3.7 Constraints

3.7.1 Field constraints

-- 员工表
CREATE TABLE emp(
id INT PRIMARY KEY,/*员工id主键,且自增长*/
ename VARCHAR(32) UNIQUE,/*员工姓名,非空且唯一*/
joindate DATE NOT NULL,/*入职日期非空*/
salary DOUBLE(7,2) NOT NULL,/*薪水,非空*/
bonus DOUBLE(7,2) DEFAULT 0/*奖金,默认为0*/
);
DESC emp;
ALTER TABLE emp CHANGE ename ename VARCHAR(32) CHARACTER set utf8;
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(1,'张三','1999-11-11',8800,5000);
SELECT * FROM emp;

3.7.2 Demonstrate primary key constraints, non-null and unique

INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(NULL,'张三','1999-11-11',8800,5000);
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(1,'张三','1999-11-11',8800,5000);
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(2,'李四','1999-11-11',8800,5000);

3.7.3 Demonstrating not-null constraints

DELETE FROM emp WHERE id = 3;
INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(3,null,'1999-11-11',8800,5000);

3.7.4 Demonstrating unique constraints

INSERT INTO emp(id,ename,joindate,salary,bonus) VALUES(3,'李四','1999-11-11',8800,5000);

3.7.5 Operations on constraints

3.7.5.1 Deleting Constraints

ALTER TABLE emp MODIFY ename VARCHAR(32) CHARACTER set utf8;

3.7.5.2 Add constraints

ALTER TABLE emp MODIFY ename VARCHAR(32) NOT NULL ;
DESC emp;
DROP TABLE emp;

3.7.5.3 Foreign key constraints (example demonstration)

-- 员工表
CREATE TABLE emp(
id INT PRIMARY KEY auto_increment,/*员工id主键,且自增长*/
name VARCHAR(32),/*员工姓名,非空且唯一*/
age INT,
dep_id INT,/*联系到拎一个表*/
-- 添加一个外键约束
CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id)
);
-- 部门表
CREATE TABLE dept(
id INT PRIMARY KEY auto_increment,
dep_name VARCHAR(32),
address VARCHAR(32)
);
DESC emp;
DESC dept;
DROP TABLE emp;
DROP TABLE dept;
ALTER TABLE emp CHANGE name name VARCHAR(32) CHARACTER set utf8;
ALTER TABLE dept CHANGE dep_name dep_name VARCHAR(32) CHARACTER set utf8;
ALTER TABLE dept CHANGE address address VARCHAR(32) CHARACTER set utf8;
INSERT INTO emp (name,age,dep_id) VALUES
('张三',20,1),
('李四',20,1),
('王五',20,1),
('赵六',20,2),
('孙七',22,2),
('周八',18,2);
INSERT INTO dept (dep_name,address) VALUES
('研发部','广州'),
('销售部','深圳');
SELECT * FROM emp;
SELECT * FROM dept;
-- 删除外键
ALTER TABLE emp DROP FOREIGN KEY fk_emp_dept;
-- 添加外键
ALTER TABLE emp ADD CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id);

4 foreign keys

Using the database, display all tables

USE db1;
SHOW TABLES;

4.1 Establishment of foreign keys

4.1.1 Many-to-many relationship

-- 订单表
CREATE TABLE tb_order(
id INT PRIMARY KEY auto_increment,
payment double(10,2),
payment_type TINYINT,
status TINYINT
);
-- 商品表
CREATE TABLE tb_goods(
id INT PRIMARY KEY auto_increment,
title VARCHAR(100),
price DOUBLE(10,2)
);
-- 中间表
CREATE TABLE tb_order_goods(
id INT PRIMARY KEY auto_increment,
order_id INT,
goods_id INT
);
-- 添加外键
ALTER TABLE tb_order_goods ADD CONSTRAINT fk_order_id FOREIGN KEY(order_id) REFERENCES tb_order(id);
ALTER TABLE tb_order_goods ADD CONSTRAINT fk_goods_id FOREIGN KEY(goods_id) REFERENCES tb_goods(id);
SHOW TABLES;

4.1.2 One-to-one relationship

-- 用户表
CREATE TABLE tb_user(
id INT PRIMARY KEY auto_increment,
photo VARCHAR(100),
name VARCHAR(32),
age INT,
sex VARCHAR(4),
desc_id INT UNIQUE,
CONSTRAINT tb_user_desc FOREIGN KEY(desc_id) REFERENCES tb_user_desc(id) 
);
-- 用户详情表
CREATE TABLE tb_user_desc(
id INT PRIMARY KEY auto_increment,
city VARCHAR(32),
edu VARCHAR(32),
income DOUBLE(7,2),
status TINYINT
);
ALTER TABLE tb_user_desc CHANGE status status VARCHAR(16) CHARACTER set utf8;
INSERT into tb_user_desc(city,edu,income,status) VALUES
('广州','本科',3000,'单身'),
('广州','硕士',12000,'单身');
INSERT into tb_user(photo,`name`,age,sex,desc_id) VALUES
('c盘','林青霞',22,'女',1),
('d盘','风清扬',24,'男',2);
ALTER TABLE tb_user auto_increment = 1;
SELECT * FROM tb_user;
SELECT * FROM tb_user_desc;
DESC tb_user;
DESC tb_user_desc;
DROP TABLE tb_user;

4.1.3 View all foreign keys

SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE;

4.2 Example Demonstration Exercise

-- 音乐专辑表名
CREATE TABLE music(
title VARCHAR(32),/*专辑名*/
alias VARCHAR(32),/*专辑别名*/
image VARCHAR(64),/*封面图片*/
style VARCHAR(16),/*流派(经典、流行、民谣)*/
type VARCHAR(8),/*类型(专辑,单曲)*/
medium VARCHAR(8),/*介质(胶片,cd)*/
publish_time DATE,/*发行时间*/
publisher VARCHAR(8),/*出版者*/
number TINYINT,/*唱片数量*/
barcode BIGINT,/*条形码*/
summary VARCHAR(1024),/*简介*/
artist VARCHAR(32),/*艺术家*/
id INT UNIQUE/*编号,唯一*/
);
-- 曲目表名
CREATE TABLE song(
name VARCHAR(32),/*歌曲名*/
serial_number TINYINT,/*歌曲序号*/
id INT UNIQUE/*编号,唯一*/
);
-- 评论表名
CREATE TABLE review(
content VARCHAR(1024),/*评论内容*/
rating TINYINT,/*评分1-5*/
review datetime,/*评论时间*/
content_user_id INT,
content_music_id INT
);
-- 用户表名
CREATE TABLE user(
username VARCHAR(32),
image VARCHAR(64),
signture VARCHAR(64),
name VARCHAR(32),
id INT PRIMARY KEY
);
-- 展示
DESC music;
DESC song;
DESC review;
DESC user;
-- 删除
DROP TABLE music;
DROP TABLE song;
DROP TABLE review;
DROP TABLE user;
-- 专辑和用户的中间表
CREATE TABLE music_user(
id INT PRIMARY KEY auto_increment,
music_id INT,
user_id INT
);
-- 添加专辑和用户外键
ALTER TABLE music_user ADD CONSTRAINT fk_music_id FOREIGN KEY(music_id) REFERENCES music(id);
ALTER TABLE music_user ADD CONSTRAINT fk_user_id FOREIGN KEY(user_id) REFERENCES user(id);
-- 添加短评和用户外键
ALTER TABLE review ADD CONSTRAINT fk_review_user FOREIGN KEY(content_user_id) REFERENCES user(id);
-- 添加短评专辑外键
ALTER TABLE review ADD CONSTRAINT fk_review_music FOREIGN KEY(content_music_id) REFERENCES music(id);
-- 添加曲目和专辑外键
ALTER TABLE song ADD CONSTRAINT fk_song_music FOREIGN KEY(id) REFERENCES music(id);
ALTER TABLE song DROP FOREIGN KEY fk_song_user;

reverse model

music

– Multi-table query

SELECT * FROM emp;
SELECT * FROM dept;
SELECT * FROM emp,dept;

– Generate Cartesian product (there are two sets of ab, remove all combinations of a and b)
– Eliminate invalid data
– Query the data of emp and dept, emp.dep_id = dept.id
– Implicit inner join

SELECT * FROM emp,dept WHERE emp.dep_id = dept.id;

– Query the name and age of emp and the dep_name of the dept table

SELECT emp.`name`,emp.age,dept.dep_name FROM emp,dept WHERE emp.dep_id = dept.id;

– Alias ​​the table

SELECT t1.`name`,t1.age,t2.dep_name FROM emp AS t1,dept AS t2 WHERE t1.dep_id = t2.id;

– explicit inner join

SELECT * FROM emp LEFT OUTER JOIN dept ON emp.dep_id = dept.id;
SELECT * FROM emp LEFT /*OUTER*/ JOIN dept ON emp.dep_id = dept.id;

– right outer join

SELECT * FROM emp RIGHT OUTER JOIN dept ON emp.dep_id = dept.id;
SELECT * FROM emp RIGHT /*OUTER*/ JOIN dept ON emp.dep_id = dept.id;

Summarize

  The above is the whole content of the SQL statement encyclopedia, I hope it will be helpful to you.

Guess you like

Origin blog.csdn.net/qq_53463544/article/details/129199700