Article directory
1. Database classification and SQL classification
-
Databases are mainly divided into two categories:
关系型数据库
and非关系型数据库
; -
Relational database: MySQL, Oracle, DB2, SQL Server, Postgre SQL, etc.;
- Relational databases are usually created by us
很多个二维数据表
; - Data tables are related to each other to form
一对一、一对多、多对多
equal relationships. - We can then use
SQL语句
the多张表中查询
data we need;
- Relational databases are usually created by us
-
Non-relational database: MongoDB, Redis, Memcached, HBse , etc.;
- The English name of non-relational database is actually Not only SQL, also referred to as
NoSQL
; - Quite speaking
非关系型数据库比较简单一些,存储数据也会更加自由
(we can even insert a complex json object directly into the database);
- The English name of non-relational database is actually Not only SQL, also referred to as
-
NoSQL is based on
Key-Value
the corresponding relationship and does not need to be passed during the query processSQL解析
;
Classification of SQL statements
DDL
(Data Definition Language): Data definition language;- You can use DDL statements to perform operations on databases or tables: create, delete, modify, etc.;
DML
(Data Manipulation Language): Data manipulation language;- Fields in the table can be added, deleted, modified, etc. through DML statements ;
DQL
(Data Query Language): Data query language;- Records can be queried from the database through DQL; (emphasis)
DCL
(Data Control Language): Data control language;- Perform related access control operations on database and table permissions;
2. SQL data types
-
The data types supported by MySQL are:
数字类型,日期和时间类型,字符串(字符和字节)类型,空间类型和 JSON数据类型
. -
Numeric type
- Integer numeric types: INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT;
- Floating point number type: FLOAT, DOUBLE (FLOAT is 4 bytes, DOUBLE is 8 bytes)
- Exact numeric types: DECIMAL, NUMERIC (DECIMAL is the implementation form of NUMERIC);
- Number of bytes occupied by integer type
-
Date type :
YEAR
Display value in YYYY format- Range 1901 to 2155, and 0000.
DATE
Type is used for values with a date part but no time part:- DATE displays values in the format YYYY-MM-DD;
- The supported range is '1000-01-01' to '9999-12-31';
DATETIME
Type for values containing date and time parts:- DATETIME displays the value in the format 'YYYY-MM-DD hh:mm:ss';
- The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59
TIMESTAMP
Data types are used for values that contain both date and time components:- TIMESTAMP displays values in the format 'YYYY-MM-DD hh:mm:ss';
- But its range is UTC time range: '1970-01-01 00:00:01' to '2038-01-19 03:14:07'
- DATETIME or TIMESTAMP values may include fractional seconds in up to microsecond (6 digits) precision
- For example, the range represented by DATETIME can be '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999'
-
string type
CHAR
The type has a fixed length when creating the table, and the length can be any value between 0 and 255;- When queried, the following spaces will be deleted;
VARCHAR
The value of type is可变长度
a string, and the length can be specified as a value between 0 and 65535;- When being queried, the following spaces will not be deleted;
-
BLOB type
- Used to store large binary types;
-
TEXT type
- Used to store large string types;
3. DDL CRUD
3.1 Library operation
- View all databases
SHOW DATABASES
- use a database
USE 数据库
- View the database currently in use
SELECT DATABASE()
- Create database
CREATE DATABASE IF NOT EXISTS 数据库名称
- Delete database
DROP DATABASE IF EXIT 数据库名称
- Modify the character set and collation of the database
ALTER DATABASE bilibili CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;
3.2 Table constraints
-
primary key constraints
PRIMARY KEY
- In a table, in order to distinguish the uniqueness of each record , there must be a field that will never be repeated and will not be empty. This field is the primary key:
- The primary key is the only index in the table ;
- and must be
NOT NULL
, if not setNOT NULL
, thenMySQL也会隐式的设置为NOT NULL
- The primary key can also be a multi-column index,
PRIMARY KEY(key_part, ...)
which we generally call a joint primary key;
- In a table, in order to distinguish the uniqueness of each record , there must be a field that will never be repeated and will not be empty. This field is the primary key:
-
only:
UNIQUE
- The fields using
UNIQUE
constraints must be different in the table and not repeated UNIQUE
Indexes allow NULL- containing columns to have multiple values NULL;
- The fields using
-
Can not be empty:
NOT NULL
- For some fields, we require users to insert values and cannot be empty. In this case, we can use NOT NULL to constrain;
-
default value:
DEFAULT
- For some fields, we want to give a default value when no value is set. In this case, we can use DEFAULT to complete
-
Auto-increment:
AUTO_INCREMENT
- We hope that some fields can be incremented without setting a value, such as user's
id
. In this case, AUTO_INCREMENT can be used to complete
- We hope that some fields can be incremented without setting a value, such as user's
-
foreign key constraints
FOREIGN KEY(外键id) REFERENCES brand(被引用的id)
3.3 Table operations
- View all datasheets
SHOW TABLES;
- View a table structure
DESC user;
- Create data table
CREATE TABLE IF NOT EXISTS `user`(
name VARCHAR(10),
age INT,
height DOUBLE
);
- Delete table
DROP TABLE IF EXISTS `user`
- Modify table name
ALTER TABLE `user` RENAME TO `t_user`
- Optimize the created user table
CREATE TABLE IF NOT EXISTS `user`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) UNIQUE NOT NULL,
sex INT DEFAULT(0),
tel VARCHAR(20)
);
- Table field operations
# 1.添加一个新的列
ALTER TABLE `user` ADD `publishTime` DATETIME;
# 2.删除一列数据
ALTER TABLE `user` DROP `updateTime`;
# 3.修改列的名称
ALTER TABLE `user` CHANGE `publishTime` `publishDate` DATE;
# 4.修改列的数据类型
ALTER TABLE `user` MODIFY `id` INT
4 DML CRUD
- Create new tables and implement basic CURD
CREATE TABLE IF NOT EXISTS `t_products`(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(20) UNIQUE NOT NULL,
description VARCHAR(200) DEFAULT '',
price DOUBLE DEFAULT 0,
publishTime DATETIME
);
-- 插入表数据
INSERT INTO `t_products` (title,description, price,publishTime) VALUES('huawei1000','描述华为',8000.0,'2012-11-9')
INSERT INTO `t_products` (title, description, price, publishTime) VALUES ('华为666', '华为666只要6666', 6666, '2166-06-06');
INSERT INTO `t_products` (title, description, price, publishTime) VALUES ('xiaomi666', 'xiaomi666只要6666', 6666, '2116-06-06');
-- 删除数据
-- 1. 删除表里面的所有数据
DELETE FROM `t_products`
-- 2. 根据条件来(id)删除语句
DELETE FROM `t_products` WHERE id=2
-- 修改数据表
-- 1. 修改表里面的所有数据
UPDATE `t_products` SET price=888;
-- 2.根据条件修改表里的数据
UPDATE `t_products` SET price=888 WHERE id=5;
-- 3.根据条件修改多个数据
UPDATE `t_products` SET price=999,description='xiaomi666只要999' WHERE id=5
-- 修改数据显示最新的更新时间,并把更新的时间也做一个记录
-- TIMESTAMP数据类型被用于同时包含日期和时间部分的值:
-- CURRENT_TIMESTAMP 记录当前的时间
ALTER TABLE `t_products` ADD `updataTime`
TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
5. DQL (Data Query Language)
- SELECT is used to retrieve selected rows (Record) from one or more tables.
- The query format is as follows
5.1 Single table query
CREATE TABLE IF NOT EXISTS `products` (
id INT PRIMARY KEY AUTO_INCREMENT,
brand VARCHAR(20),
title VARCHAR(100) NOT NULL,
price DOUBLE NOT NULL,
score DECIMAL(2,1),
voteCnt INT,
url VARCHAR(100),
pid INT
);
-- 查询
-- 1.查询所有
SELECT * FROM `products`
-- 2. 查询指定的字段 price title brand
SELECT price, title,brand FROM `products`
-- 3 别名查询 as ,同时as关键字也是可以省略...
SELECT price as productsPrice, title productsTitle,brand FROM `products`
-- 条件查询-比较运算符
SELECT*FROM `products` WHERE price<1000
SELECT*FROM `products` WHERE price=939
SELECT*FROM `products` WHERE brand='小米'
-- 查询条件,逻辑运算符
-- 1. and 关键字与 && 一样
SELECT*FROM `products` WHERE brand='小米' AND price=939
-- 2. 逻辑或 or
SELECT*FROM `products` WHERE brand='华为' || price>=8000
-- 区间范围查询
-- 1. 关键字 BETWEEN AND
SELECT*FROM `products` WHERE price>=1000 && price<=2000
SELECT*FROM `products`WHERE price BETWEEN 1000 AND 2000
-- 枚举出多个结果,其中之一
SELECT*FROM `products` WHERE brand='小米' OR brand='华为'
SELECT*FROM `products` WHERE brand IN('小米','华为')
-- 模糊查询link 与特殊符号 % 与
-- 1. 查询title以v开头
SELECT * FROM `products` WHERE title LIKE 'v%';
-- 2.查询带M的title
SELECT * FROM `products` WHERE title LIKE '%M%';
-- 3.查询带M的title必须是第三个字符 (前面字符利用 _ )既下划线
SELECT * FROM `products` WHERE title LIKE '__M%';
-- 排序 ORDER BY
-- DESC:降序排列;
-- ASC:升序排列;
-- 1.价格小于1000 降序
SELECT * FROM `products` WHERE price < 1000 ORDER BY price ASC
-- 分页查询 用法[LIMIT {[offset,] row_count | row_count OFFSET offset}]
-- 1.limit 限制20条数据
SELECT * FROM `products` LIMIT 20
-- 2. OFFSET 偏移数据 (重第41条数据开始查询,查询20条)
SELECT * FROM `products` LIMIT 20 OFFSET 40
-- 另外一种写法:offset, row_count
SELECT * FROM `products` LIMIT 40, 20
5.2 Aggregation query and group query
- In the group query, if
Group By
some constraints are added to the query results, then we can use:HAVING
.
-- 1. 计算华为手机的平均价格
SELECT AVG(price) FROM `products` WHERE brand='华为'
-- 2.所有手机的平均分数
SELECT AVG(score) FROM `products`
-- 3.手机中最低和最高分数
SELECT MAX(score) FROM `products`;
SELECT MIN(score) FROM `products`;
-- 4.计算总投票人数
SELECT SUM(voteCnt) FROM `products`;
-- 5.计算 华为手机的个数
SELECT COUNT(*) FROM `products` WHERE brand = '华为'
-- 6. 分组 GROUP BY
-- 6.1 对品牌进行分组
SELECT brand FROM `products` GROUP BY brand
-- 6.2 分组后查看最低和最高的手机价格
-- ROUND 保留的小数ROUND(AVG(price),2)
SELECT brand,MAX(price),MIN(price) FROM `products` GROUP BY brand
-- 6.3 分组查询后进行价格最大值的约束 HAVING
SELECT brand,MAX(price) AS priceMAX,MIN(price) AS priceMin FROM `products` GROUP BY brand HAVING priceMAX > 4000
5.3 Multi-table query and foreign key constraints
- Update and delete data parsing when foreign key exists
RESTRICT
(Constraint): When deleting the corresponding record in the parent table (that is, the source table of the foreign key), first check whether the record has a corresponding foreign key, and if so, deletion is not allowed.NO ACTION
: Consistent with RESTRICT, that is, if slave data exists, master data is not allowed to be deleted.CASCADE
: When a record is updated or deleted, it will be checked whether the record has an associated foreign key record. If so:- Update: Then the corresponding record will be updated;
- Delete: Then the associated records will be deleted together;
SET NULL
: When a record is updated or deleted, it will be checked whether the record has an associated foreign key record. If so, the corresponding value will be set to NULL.
-- 多张表的查询
CREATE TABLE IF NOT EXISTS `t_song`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
duration INT DEFAULT 0,
singer VARCHAR(10)
-- 外键约束 这里的意思是singer_id 是外键约束 约束需要引入brand这个表里面的id
-- singer_id INT,
-- FOREIGN KEY(singer_id) REFERENCES brand(id)
);
INSERT INTO `t_song` (name,duration,singer) VALUES('爸爸妈妈',100,'李荣浩')
INSERT INTO `t_song` (name,duration,singer) VALUES('戒烟',120,'李荣浩')
INSERT INTO `t_song` (name,duration,singer) VALUES('从前的那个少年',100,'李荣浩')
-- 2.创建歌手表
CREATE TABLE IF NOT EXISTS `t_singer`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10),
intro VARCHAR(200)
)
-- 插入数据
INSERT INTO `t_singer` (name, intro) VALUES ('五月天', '五月天,全亚洲代表性摇滚乐团。演出足迹踏遍美国,澳洲以及全亚洲地区.')
INSERT INTO `t_singer` (name, intro) VALUES ('李荣浩', '李荣浩,全亚洲代表歌曲制作。')
-- 3.修改歌曲表
ALTER TABLE `t_song` DROP `singer`;
ALTER TABLE `t_song` ADD `singer_id` INT;
多表查询
-- 4.为了品牌单独创建一张表并插入数据
CREATE TABLE IF NOT EXISTS `brands`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10) UNIQUE NOT NULL,
website VARCHAR(100),
worldRank INT
);
INSERT INTO `brands` (name, website, worldRank) VALUES ('华为', 'www.huawei.com', 1);
INSERT INTO `brands` (name, website, worldRank) VALUES ('小米', 'www.mi.com', 10);
INSERT INTO `brands` (name, website, worldRank) VALUES ('苹果', 'www.apple.com', 5);
INSERT INTO `brands` (name, website, worldRank) VALUES ('oppo', 'www.oppo.com', 15);
INSERT INTO `brands` (name, website, worldRank) VALUES ('京东', 'www.jd.com', 3);
INSERT INTO `brands` (name, website, worldRank) VALUES ('Google', 'www.google.com', 8);
-- 4.1外键约束
-- 为products表添加brand_id
ALTER TABLE `products` ADD `brand_id` INT
-- 为外键添加约束 并引用表brand中的id字段 REFERENCES brand(id)=>引用brands中的id
ALTER TABLE `products` ADD FOREIGN KEY (brand_id) REFERENCES brands(id);
-- 4.2 将products中的brand_id关联到brand中的id的值
UPDATE `products` SET `brand_id` = 1 WHERE `brand` = '华为';
UPDATE `products` SET `brand_id` = 4 WHERE `brand` = 'OPPO';
UPDATE `products` SET `brand_id` = 3 WHERE `brand` = '苹果';
UPDATE `products` SET `brand_id` = 2 WHERE `brand` = '小米';
-- 5. 外键约束的情况下修改
UPDATE `brands` SET id=100 WHERE id=1
-- 1451 - Cannot delete or update a parent row: a foreign key constraint fails (`music_db`.`products`, CONSTRAINT `products_ibfk_1` FOREIGN KEY (`brand_id`) REFERENCES `brands` (`id`)) 报错误
-- 6. 查看表中的外键
SHOW CREATE TABLE `products`
-- 7. 删除外键
ALTER TABLE `products` DROP FOREIGN KEY products_ibfk_1;
-- 8 添加外键,当外键删除或者更新时 引用应该删除或者更新
ALTER TABLE `products` ADD FOREIGN KEY (brand_id) REFERENCES brands(id)
ON UPDATE CASCADE
ON DELETE CASCADE;
UPDATE `brands` SET id=100 WHERE id=1
5.4 Connection query between multiple tables
- When querying data, because the data exists in multiple tables, multi-table queries need to be combined
- for example:
SELECT * FROM `products`, `brand`
- At this time, all the data from the two tables will be queried, and a total
648
of pieces of data will be retrieved. - This will combine each piece of data in the first table with each piece of data in the second table;
- This result we call
笛卡尔乘积
, also call直积
, expressed asX*Y
; - However, most of the above query results are meaningless and not what we need, so we will use
连接查询
5.4.1 Left link query
- If we want to get all the data on the left (mainly the left table)
- At this time, it means that no matter whether the left table has a corresponding brand_id value corresponding to the id of the right table, the data on the left will be queried;
- The complete writing is
LEFT [OUTER] JOIN
,OUTER可以省略
but
-- 3.左链接 LEFT [OUTER] JOIN "表" ON 连接条件
-- 这个时候就表示无论左边的表是否有对应的brand_id的值对应右边表的id,左边的数据都会被查询出来;
SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id=brands.id
-- 3.1 查询不为null有交集的数据
SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id = brands.id WHERE brands.id IS NOT NULL;
5.4.2 Right join query
- If we want to get all the data on the right (mainly the right table) :
- At this time, it means that no matter whether the brand_id in the left table corresponds to the id in the right table, the data on the right will be queried;
- The complete writing method is
RIGHT [OUTER] JOIN
, but OUTER can be omitted;
SELECT * FROM `products` RIGHT JOIN `brands` ON products.brand_id=brands.id
5.4.3 Inner join
- The upper inner join means that the table on the left and the table on the right have corresponding data associations:
- You can write
CROSS JOIN
either wayJOIN
;
- You can write
SELECT * FROM `products` JOIN `brands` ON `products`.brand_id = `brands`.id
- where written internal connection
SELECT * FROM `products`, `brand` WHERE `products`.brand_id = `brand`.id
- Comparison of the above SQL statements
- Inner join means that when two tables are connected, the relationship between the data will be constrained to determine the results of subsequent queries.
- The where condition means first calculating the Cartesian product, and then selecting the where condition based on the data of the Cartesian product.
5.4.4 Full connection
- Full join is used in the SQL specification
FULL JOIN
, but there is no support for it in MySQL. We need to useUNION
to achieve it:
(SELECT * FROM `products` LEFT JOIN `brands` ON `products`.brand_id = `brands`.id)
UNION
(SELECT * FROM `products` RIGHT JOIN `brands` ON `products`.brand_id = `brands`.id)
(SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id = brands.id WHERE brands.id IS NULL)
UNION
(SELECT * FROM `products` RIGHT JOIN `brands` ON products.brand_id = brands.id WHERE products.id IS NULL)
- Join query summary
-- 在查询到产品的同时,显示对应的品牌相关的信息,因为数据是存放在两张表中,所以这个时候就需要进行多表查询
-- //1. 这种默认做法会发生这个表的数据与另一个表的数据会相乘 得到 M*N的数据
SELECT * FROM `products`, `brands`;
-- 2.过滤查询
SELECT * FROM `products`, `brands` WHERE products.brand_id=brands.id;
-- 3.左链接 LEFT [OUTER] JOIN "表" ON 连接条件
-- 这个时候就表示无论左边的表是否有对应的brand_id的值对应右边表的id,左边的数据都会被查询出来;
SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id=brands.id
-- 3.1 查询不为null有交集的数据
SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id = brands.id WHERE brands.id IS NOT NULL;
-- 4. 右连接 RIGHT [OUTER] JOIN "表" ON 连接条件
-- 这个时候就表示无论左边的表中的brand_id是否有和右边表中的id对应,右边的数据都会被查询出来
SELECT * FROM `products` RIGHT JOIN `brands` ON products.brand_id=brands.id
-- 5. 内连接 CROSS JOIN或者 JOIN;
-- 5.1内连接效果和下面where查询效果一样的,但是做法确是不一样的
-- 5.1.1SQL语句一:内连接,代表的是在两张表连接时就会约束数据之间的关系,来决定之后查询的结果;
-- 5.1.2SQL语句二:where条件,代表的是先计算出笛卡尔乘积,在笛卡尔乘积的数据基础之上进行where条件的帅选
SELECT * FROM `products` JOIN `brands` ON `products`.brand_id = `brands`.id
SELECT * FROM `products`, `brands` WHERE `products`.brand_id = `brands`.id;
-- 6. 全连接
-- 6.1 SQL规范中全连接是使用FULL JOIN,但是MySQL中并没有对它的支持,我们需要使用 UNION 来实现
(SELECT * FROM `products` LEFT JOIN `brands` ON `products`.brand_id = `brands`.id)
UNION
(SELECT * FROM `products` RIGHT JOIN `brands` ON `products`.brand_id = `brands`.id)
(SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id = brands.id WHERE brands.id IS NULL)
UNION
(SELECT * FROM `products` RIGHT JOIN `brands` ON products.brand_id = brands.id WHERE products.id IS NULL)
5.5 Many-to-many table query
Reference article-many-to-many analysis
-- 1.多对多关系
-- 1.1. 创建学生表
CREATE TABLE IF NOT EXISTS `students`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
age INT
);
INSERT INTO `students` (name, age) VALUES('why', 18);
INSERT INTO `students` (name, age) VALUES('tom', 22);
INSERT INTO `students` (name, age) VALUES('lilei', 25);
INSERT INTO `students` (name, age) VALUES('lucy', 16);
INSERT INTO `students` (name, age) VALUES('lily', 20);
-- 1.2. 创建课程表
CREATE TABLE IF NOT EXISTS `courses`(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
price DOUBLE NOT NULL
);
INSERT INTO `courses` (name, price) VALUES ('英语', 100);
INSERT INTO `courses` (name, price) VALUES ('语文', 666);
INSERT INTO `courses` (name, price) VALUES ('数学', 888);
INSERT INTO `courses` (name, price) VALUES ('历史', 80);
INSERT INTO `courses` (name, price) VALUES ('物理', 100);
-- 1.3. 学生选择的课程关系表
CREATE TABLE IF NOT EXISTS `students_select_courses`(
id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT NOT NULL,
course_id INT NOT NULL,
-- 外键约束
FOREIGN KEY (student_id) REFERENCES students(id) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (course_id) REFERENCES courses(id) ON UPDATE CASCADE ON DELETE CASCADE
);
-- 2 选课情况
-- 2-1 why 选修了 英文和数学
INSERT INTO `students_select_courses` (student_id, course_id) VALUES (1, 1);
INSERT INTO `students_select_courses` (student_id, course_id) VALUES (1, 3);
-- 2-2 lilei选修了 语文和数学和历史
INSERT INTO `students_select_courses` (student_id, course_id) VALUES (3, 2);
INSERT INTO `students_select_courses` (student_id, course_id) VALUES (3, 3);
INSERT INTO `students_select_courses` (student_id, course_id) VALUES (3, 4);
-- 3查询数据
-- 3.1 所有学生的选课情况(内连接) students_select_courses(内连接属性)
SELECT * FROM `students`
JOIN `students_select_courses` ON students.id= students_select_courses.student_id
JOIN `courses` ON students_select_courses.course_id=courses.id
-- 3.2 别名查询名称
SELECT
stu.name stuName , cou.name couName
FROM `students` stu
JOIN `students_select_courses` ON stu.id= students_select_courses.student_id
JOIN `courses` cou ON students_select_courses.course_id=cou.id
-- 3.3左链接
SELECT
stu.name stuName , cou.name couName
FROM `students` stu
LEFT JOIN `students_select_courses` ON stu.id= students_select_courses.student_id
LEFT JOIN `courses` cou ON students_select_courses.course_id=cou.id
-- 3.4 单个学生选择课程情况 (左连接可以保证,在学生没有选择课的情况也可以显示)
SELECT
stu.name stuName , cou.name couName
FROM `students` stu
LEFT JOIN `students_select_courses` ON stu.id= students_select_courses.student_id
LEFT JOIN `courses` cou ON students_select_courses.course_id=cou.id WHERE stu.id=1
-- 3.5 查询哪些学生没有选择课程
SELECT
stu.name stuName , cou.name couName
FROM `students` stu
LEFT JOIN `students_select_courses` ON stu.id= students_select_courses.student_id
LEFT JOIN `courses` cou ON students_select_courses.course_id=cou.id WHERE cou.id is NULL
-- 3.6查询哪些课程没有被学生选择
SELECT
stu.name stuName , cou.name couName
FROM `students` stu
RIGHT JOIN `students_select_courses` ON stu.id= students_select_courses.student_id
RIGHT JOIN `courses` cou ON students_select_courses.course_id=cou.id WHERE cou.id is NULL
6 Query object array
- Requirement: When performing multi-table queries, the data in Table 1 will be treated as a subset of the data in Table 2
- Requirement 2: When querying multiple tables, the brand information table will be placed in a separate object and displayed in the product table.
- Requirement 3: When querying multiple tables, the learning course selection information will be placed in an array object.
JSON_OBJECT
transfer objectJSON_ARRAYAGG和JSON_OBJECT
Many to many to array
-- 1. 单表查询
SELECT * FROM `products` WHERE price>5000
-- 2. 多表查询
SELECT * FROM `products` LEFT JOIN `brands` ON products.brand_id=brands.id
WHERE price>5000
-- 3. 多表查询:品牌信息放到一个单独的对象中
-- 格式 JSON_OBJECT([key, val[, key, val] ...])
SELECT
products.id as pid,products.title as title,products.price as price,
JSON_OBJECT('id',brands.id,'name',brands.name,'website',brands.website) as brand
FROM `products` LEFT JOIN `brands` ON products.brand_id=brands.id
WHERE price>5000
-- 多对多查询
SELECT * FROM `students` as stu
LEFT JOIN `students_select_courses` as ssc ON ssc.student_id=stu.id
LEFT JOIN `courses` as cu ON ssc.course_id =cu.id WHERE cu.id IS NOT NULL
-- 多对多查询分组合并
-- JSON_ARRAYAGG 转为数组对象
SELECT
stu.id as id, stu.name as name, stu.age as age,
JSON_ARRAYAGG(JSON_OBJECT('id',cs.id,'name',cs.name,'price',cs.price)) as course
FROM `students` as stu
LEFT JOIN `students_select_courses` as ssc ON ssc.student_id=stu.id
LEFT JOIN `courses` as cs ON ssc.course_id =cs.id WHERE cs.id IS NOT NULL
GROUP BY stu.id