3.2 Query results are not repeated DISTINCT
3.5 Limit the number of query results
3.9 Alias AS for fields or tables
3.10 Query REGEXP using regular expressions
4 Adding, deleting and modifying data
5.2 Create an index when creating a table
5.3 Create an index on an existing table
A foreign key is a field in a table, which may not be the primary key of this table, but corresponds to the primary key of another table.
After the foreign key is defined, the rows that have an association relationship in another table will not be deleted.
The main function of foreign keys is to ensure the integrity of data references.
The unique constraint requires the field to be unique, it is allowed to be empty but it can only appear once
The default value when the field is not assigned
The attribute value is automatically increased
A table can only have one field to set the attribute value to automatically increase, and the field must be part of the primary key, and the field type needs to be any integer
CREAT TABLE tb_emp
(
id INT(11) PRIMARY KEY ATUO_INCREMENT, // 主键约束,自增
name VARCHAR(25) NOT NULL, // 非空约束
id_card INT(13) UNIQUE, // 唯一约束
deptId INT(11) DEFAULT 111, // 默认约束
salary FLOAT,
// 定义完成后指定约束
CONSTRAINT fk_emp _empDept FOREIGN KEY(deptId) REFERENCES tb_dept(id) // 外键约束
[
PRIMARY KEY (name,id_card), // 联合主键
CONSTRAINT STH UNIQUE (id_card), // 唯一约束
]
)
DESC 表名
SHOW CREATE TABLE 表名\G
SELECT name LIKE '%三_' FROM emp
3.2 Query results are not repeated DISTINCT
SELECT DISTINCT name FROM emp; // 查询获取不重复的姓名
SELECT * FROM empt ORDER BY deptId,salary DESC; //先按照deptId排序,后按照salary排序
GROUP BY is often used with aggregate functions, for example: MAX(), MIN(), COUNT(), SUM(), AVG() etc.
// 按照s_id排序 并统计种类大于1的每种水果
SELECT s_id, GROUP_CONCAT(f_name) AS name
FROM fruits
GROUP BY s_id HAVING COUNT(f_name) > 1;
SELECT s_id, COUNT(*) AS total
FROM fruits
GROUP BY s_id WITH ROLLUP; // WITH ROLLUP 对分组结果进行统计
SELECT * FROM fruits GROUP BY s_id, s_name; // 层次分组 先按 s_id 排序分组,后按 s_name 排序分组
Sort groups
SELECT s_id, SUM(quantity * item_price) AS total
FROM fruits
GROUP BY s_id
HAVING SUM(quantity * item_price) > 100
ORDER BY total ; // 按照总价格 total 排序分组结果
3.5 Limit the number of query results
SELECT * FROM fruits LIMIT 4; // 查询前四行
SELECT * FROM fruits LIMIT 4, 3; // 从第5条记录开始,查询三行(5,6,7)
Avoid too many connection queries in a high concurrency environment
SELECT c.c_id, o.o_num
FROM customers c LEFT JOIN orders o
ON c.c_id = o.c_id
MySQL does not support FULL OUTER JOIN, it can be implemented using union
3.7 Subqueries
The result in the subquery is often used as the filter condition of another query in the outer layer
Commonly used matching operators for subqueries are: ANY, ALL, IN, EXISTS
SELECT num1 FROM tb1 WHERE num1 > ANY(SELECT num2 FROM tb2);
// 如果suppliers表中存在 s_id = 107 的供应商,则查询 fruits表中 f_price > 10 的记录
SELECT * FROM fruits
WHERE f_price > 10 AND [NOT] EXISTS
(SELECT s_name FROM suppliers WHERE s_id = 107)
// 查询fruits中 由 suppliers 供应商提供的水果数据
SELECT * FROM fruits
WHERE s_name [NOT] IN
(SELECT s_name FROM suppliers)
3.8 Combined query UNION
Combine the results of multiple SELECTs into a single result set. The number of columns and data types corresponding to the two tables must be the same when merging
UNION deletes duplicate records, and the returned rows are unique
UNION ALL does not delete duplicate rows
SELECT s_id, f_name, f_price
FROM fruits
WHERE f_price < 9.0
UNION [ALL]
SELECT s_id, f_name, f_price
FROM fruits
WHERE s_id IN(101,103);
3.9 Alias AS for fields or tables
SELECT f1.f_name AS fruit_name, f1.f_price AS fruit_price
FROM fruits AS f1
WHERE f1.f_price < 8;
3.9 Query REGEXP using regular expressions
SELECT * FROM fruits WHERE f_name REGEXP '^b';
4 Adding, deleting and modifying data
// 插入一条
INSERT INTO person (age,name,password) VALUES (22,'小明','123456');
// 插入多条
INSERT INTO person (age,name,password)
VALUES (22,'小明','123456'),
(23,'小红','123456'),
(24,'小白','123456');
// 将查询结果插入
INSERT INTO person (age,name,password)
SELECT age,name,password FROM person WHERE id = 5;
Note that updating without writing the conditional clause will update all records in the table
UPDATE person SET info='student',password='12345 WHERE age BETWEEN 7 AND 18;
Note that deleting the conditional clause without writing will delete all records in the table
UPDATE person SET info='student',password='12345 WHERE age BETWEEN 7 AND 18;
(1) Indexes are not as many as possible. Indexes will affect the performance of additions, deletions, and modifications, avoiding too many indexes on tables that are frequently added, deleted, and modified;
(2) Indexes should be created for fields that are frequently used for queries. Composite indexes are better than single-column indexes, and the index columns of composite indexes are as few as possible;
(3) Do not create indexes for tables with small amounts of data;
(4) Do not create indexes on columns with few different values;
(5) When uniqueness is the essence of certain data, specify a unique index;
(6) Establish indexes on columns that are frequently sorted or grouped
Index naming rules: idx_ field name 1 field name 2 field name 3
Note: The order of the index is consistent with the order of the fields when the index is created
5.2 Create an index when creating a table
CREAT TABLE tb_emp
(
id INT(11) PRIMARY KEY ATUO_INCREMENT, // 主键约束,自增
name VARCHAR(25) NOT NULL, // 非空约束
age INT(3),
idCard INT(13) UNIQUE, // 唯一约束
deptId INT(11) DEFAULT 111, // 默认约束
salary FLOAT,
address VARCHAR(250),
INDEX idx_name(name), // 单列索引
INDEX idx_nameAgeSalary(name,age,aslary), // 组合索引
UNIQUE INDEX idx_idCard(idCard) // 唯一索引
);
5.3 Create an index on an existing table
Method 1: ALTER TABLE statement
ALTER TABLE 表名 ADD INDEX 索引名 (字段); // 单列索引
ALTER TABLE 表名 ADD INDEX 索引名 (字段1,字段2,字段3); // 组合索引
ALTER TABLE 表名 ADD UNIQUE INDEX 索引名 (字段); // 唯一索引
Method 2: CREATE INDEX statement
CREATE INDEX 索引名 ON 表名(字段); // 单列索引
CREATE INDEX 索引名 ON 表名(字段1,字段2,字段3); // 组合索引
CREATE UNIQUE INDEX 索引名 ON 表名(字段); // 唯一索引
SHOW INDEX FROM 表名 [\G];
If the deleted column is part of the index, delete the column, the column will also be deleted from the index;
If all the columns of the index are deleted, the index will be deleted.
Method 1: ALTER TABLE statement
ALTER TABLE 表名 DROP INDEX 索引名;
Method 2: DROP INDEX statement
DROP INDEX 索引名 ON 表名
The view is a virtual table, a table derived from one or more tables
View function: simplicity (what you see is what you need), security (through the view users can only query and modify the data they can see)
When the data seen by the view is modified, the data of the corresponding basic table will also change, and the associated view will change; when the data of the basic table changes, these changes will be automatically mapped to the view
CREATE VIEW v_t AS SELECT name,age,salary FROM person;
// 创建视图时重命名
CREATE VIEW v_person(v_name,v_age,v_salary) AS SELECT name,age,salary FROM person;
// 基于多表创建视图
CREATE VIEW v_personDept(v_name,v_age,v_salary,v_dept) AS
SELECT p.name,p.age,p.salary,d.name FROM person p, dept d WHERE p.d_id = d.id;
DESCRIBE 视图名称
CREATE OR REPLACE VIEW 视图名称 AS 查询语句 // 视图存在则更新,不存在则创建
CREATE OR REPLACE VIEW view1 AS SELECT * FROM person
ALTER VIEW view1 AS SELECT * FROM person
DROP VIEW [IF EXISTS] 视图1[,视图2,视图3...]
View additions, deletions, modifications, and common tables
// 备份
mysqldump -u 用户名 -h 主机 -p 密码 数据库[表1[,表2,表3...]] > 文件全路径/文件名.sql
// 恢复
mysql -u 用户名 -p 密码 [数据库] < 文件全路径/文件名.sql