MySQL Basics - Introduction to SQL

This article introduces the general syntax of SQL in MySQL, including: DDL, DML, DQL, DCL

Reference documents:

SQL classification

SQL statements in MySQL are not case-sensitive, and it is recommended to use capital letters for keywords

Classification full name illustrate
DDL Data Definition Language Data Definition Language, used to define database objects (databases, tables, fields)
DML Data Manipulation Language Data manipulation language, used to add, delete, and modify data in database tables
DQL Data Query Language Data query language, used to query the records of tables in the database
DCL Data Control Language Data control language, used to create database users and manage permissions

DDL (Data Definition Language)

database operation

查询所有数据库:
SHOW DATABASES;

查询当前数据库:
SELECT DATABASE();

创建数据库:
CREATE DATABASE [ IF NOT EXISTS ] 数据库名 [ DEFAULT CHARSET 字符集] [COLLATE 排序规则 ];

删除数据库:
DROP DATABASE [ IF EXISTS ] 数据库名;

使用数据库:
USE 数据库名;

table operation

查询当前数据库所有表:
SHOW TABLES;

查询表结构:
DESC 表名;

查询指定表的建表语句:
SHOW CREATE TABLE 表名;

表修改操作:
ALTERTABLE 表名 ADD/MODIFY/CHANGE/DROP/RENAME TO...;
添加字段:ALTER TABLE 表名 ADD 字段名 类型(长度) [COMMENT 注释] [约束];
修改数据类型:ALTER TABLE 表名 MODIFY 字段名 新数据类型(长度);
修改字段名和字段类型:ALTER TABLE 表名 CHANGE 旧字段名 新字段名 新数据类型(长度) [COMMENT 注释] [约束];
修改表名:ALTER TABLE 表名 RENAME TO 新表名;
删除字段:ALTER TABLE 表名 DROP 字段名;

删除表:
DROP TABLE 表名;

删除指定表,并重新创建该表:
TRUNCATE TABLE 表名;
CREATE TABLE 表名称(
		字段1 类型 [COMMENT 字段1注释],
		字段2 类型 [COMMENT 字段2注释],
		...
		字段n 类型 [COMMENT 字段n注释]
)[COMMENT 表注释];

DML (Data Manipulation Language)

adding data

指定字段插入数据:
INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (1,2, ...);
全部字段:
INSERT INTO 表名 VALUES (1,2, ...);

批量添加数据:
INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (1,2, ...), (1,2, ...), (1,2, ...);
INSERT INTO 表名 VALUES (1,2, ...), (1,2, ...), (1,2, ...);

Precautions:

  • When inserting data, the specified field order needs to correspond to the value order one-to-one
  • String and date type data should be enclosed in quotes
  • The size of the inserted data should be within the specified range of the field

Update and delete data

修改指定字段的数据:
UPDATE 表名 SET 字段名1 =1, 字段名2 =2, ... [ WHERE 条件 ];
比如:
UPDATE emp SET name = 'Jack' WHERE id = 1;

删除数据:
DELETE FROM 表名 [ WHERE 条件 ];

Notice:

  • The condition of the modification statement can be present or not. If there is no condition, all data in the entire table will be modified
  • The conditions of the DELETE statement may or may not be present. If WHERE is not added, the data in the entire table is deleted.
  • The DELETE statement cannot delete the value of a certain field, but UPDATE can be used.

DQL

grammar:

SELECT
	字段1,
	字段2,
	...
FROM
	表1,2,
	...
WHERE
	条件1,
	条件2,
	...
GROUP BY
	分组字段1,
	分组字段2,
	...
HAVING
	分组后条件1,
	分组后条件2,
	...
ORDER BY
	排序字段1,
	排序字段2,
	...
LIMIT
	分页参数

basic query

Query multiple fields:
SELECT 字段1, 字段2, 字段3, ... FROM 表名;
SELECT * FROM 表名;

Set an alias:
SELECT 字段1 [ AS 别名1 ], 字段2 [ AS 别名2 ], 字段3 [ AS 别名3 ], ... FROM 表名;
SELECT 字段1 [ 别名1 ], 字段2 [ 别名2 ], 字段3 [ 别名3 ], ... FROM 表名;

Remove duplicate records:
SELECT DISTINCT 字段列表 FROM 表名;

Escaping:
SELECT * FROM 表名 WHERE name LIKE '/_张三' ESCAPE '/'
_ after / is not used as a wildcard

conditional query

grammar:
SELECT 字段列表 FROM 表名 WHERE 条件列表;
insert image description here
insert image description here

-- 年龄等于30
select * from employee where age = 30;

-- 年龄小于30
select * from employee where age < 30;

-- 小于等于
select * from employee where age <= 30;

-- 没有身份证
select * from employee where idcard is null or idcard = '';

-- 有身份证
select * from employee where idcard;
select * from employee where idcard is not null;

-- 不等于
select * from employee where age != 30;

-- 年龄在2030之间
select * from employee where age between 20 and 30;
select * from employee where age >= 20 and age <= 30;

-- 下面语句不报错,但查不到任何信息
select * from employee where age between 30 and 20;

-- 性别为女且年龄小于30
select * from employee where age < 30 and gender = '女';

-- 年龄等于253035
select * from employee where age = 25 or age = 30 or age = 35;
select * from employee where age in (25, 30, 35);

-- 姓名为两个字
select * from employee where name like '__';

-- 身份证最后为X
select * from employee where idcard like '%X';

aggregate query (aggregate function)

grammar:SELECT 聚合函数(字段) FROM 表名;

Common aggregate functions:
insert image description here

#统计该企业员工数量
SELECT COUNT(*) FROM emp;
#或
SELECT COUNT(字段) FROM emp; 

#统计该企业员工的平均年龄
SELECT ROUND(AVG(age),0) FROM emp; #这里的ROUND是四舍五入,其中0是保留几位小数,从0开始。

#统计该企业员工最大年龄
SELECT MAX(age) FROM emp;

#统计该企业员工最小年龄
SELECT MIN(age) FROM emp;

#统计北京市员工年龄之和以及平均值
SELECT workaddress as '工作地址',SUM(age) as '北京地区年龄之和',AVG(age) as '北京地区年龄平均值' FROM emp WHERE workaddress = '北京市';

Notice:

  • All NULL values ​​do not participate in the calculation of aggregate functions.

Group query

Syntax: SELECT 字段列表 FROM 表名 [WHERE 条件] GROUP BY 字段名 [HAVING 过滤条件]
The difference between where and having:

  • The execution timing is different: where is to filter before grouping, and not to participate in grouping if the where condition is not met; having is to filter the results after grouping.
  • The judgment conditions are different: where cannot judge the aggregation function, but having can.

example:

-- 根据性别分组,统计男性和女性数量(只显示分组数量,不显示哪个是男哪个是女)
select count(*) from employee group by gender;

-- 根据性别分组,统计男性和女性数量
select gender, count(*) from employee group by gender;

-- 根据性别分组,统计男性和女性的平均年龄
select gender, avg(age) from employee group by gender;

-- 年龄小于45,并根据工作地址分组
select workaddress, count(*) from employee where age < 45 group by workaddress;

-- 年龄小于45,并根据工作地址分组,获取员工数量大于等于3的工作地址
select workaddress, count(*) address_count from employee where age < 45 group by workaddress having address_count >= 3;

Precautions:

  • Execution order: where > aggregate function > having
  • After grouping, the fields to be queried are generally aggregation functions and grouping fields, and it is meaningless to query other fields

Sort query

grammar:
SELECT 字段列表 FROM 表名 ORDER BY 字段1 排序方式1, 字段2 排序方式2;

sort by:

  • ASC: ascending order (default)
  • DESC: descending order

Notice:

  • If it is multi-field sorting, when the first field has the same value, it will be sorted according to the second field.
#根据年龄对员工进行升序排序
SELECT * FROM emp ORDER BY age ASC;

#根据入职时间,对员工进行降序排序
SELECT * FROM emp ORDER BY entrydate DESC;

#根据年龄对员工进行升序排序,年龄相同再根据入职时间降序排序
SELECT * FROM emp ORDER BY age ASC, entrydate DESC;

Paging query

Syntax: SELECT 字段1, 字段2, ... FROM 表名 LIMIT 起始索引, 查询的记录条数;
Note:

  • The starting index starts from 0, starting index = (query page number - 1) * number of records to be queried.
  • Pagination query is a database dialect, and different databases have different implementations. In MySQL, it is LIMIT.
  • If the data of the first page is queried, the starting index can be ignored.

example:

#查询第16页员工数据,每页显示50条数据
SELECT * FROM emp LIMIT 750, 50;

#查询年龄为20212223岁的员工信息
SELECT * FROM emp WHERE age BETWEEN 20 AND 23;

#查询性别为男,年龄在30-50岁(含)且名字为三个字的员工
SELECT name,age FROM emp WHERE age BETWEEN 30 AND 50 AND name LIKE '___';

#统计员工表中,年龄小于50的男性员工和女性员工人数。
SELECT gender,COUNT(*) FROM emp WHERE age < 50 GROUP BY gender; 

#查询所有年龄小于等于35岁员工的姓名和年龄,并对查询结果根据年龄升序排序,如果年龄相同按入职时间降序排序
SELECT name,age FROM emp WHERE age <= 35 ORDER BY age, entrydate DESC;

#查询性别为男,且年龄在30-50岁(含)以内的前20个员工信息,对结果按年龄升序排序,如果年龄相同按入职时间升序排序
SELECT * FROM emp WHERE age BETWEEN 30 AND 50 ORDER BY age, entrydate LIMIT 20;

order of execution

  • Writing order:SELECT -> FROM -> WHERE -> GROUP BY -> HAVING -> ORDER BY -> LIMIT

  • Execution order:FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT

DCL (Data Control Language)

manage users

Query users:
USE mysql;
SELECT * FROM user;

Create user:
CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码';

Modify user password:
ALTER USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '新密码';

delete users:
DROP USER '用户名'@'主机名';

example:

-- 创建用户test,只能在当前主机localhost访问
create user 'test'@'localhost' identified by '123456';

-- 创建用户test,能在任意主机访问
create user 'test'@'%' identified by '123456';
create user 'test' identified by '123456';

-- 修改密码
alter user 'test'@'localhost' identified with mysql_native_password by '1234';

-- 删除用户
drop user 'test'@'localhost';

Precautions

  • Hostnames can use % wildcards

access control

insert image description here
Permissions - Query Permissions
Syntax:SHOW GRANTS FOR '用户名'@'主机名';

Permissions - grant permissions
Syntax:GRANT 权限 ON 数据库名.表名 TO '用户名'@'主机名';

permission-revoke permission
Syntax:REVOKE 权限 ON 数据库名.表名 FROM '用户名'@'主机名';

Notice:

  • Separate multiple permissions with commas.
  • When authorizing, the database name and table name can be wildcarded with '**', representing all.

Guess you like

Origin blog.csdn.net/baidu_33256174/article/details/130670019