MySQL-1-SQL Explanation

B station learning video source

SQL

SQL general syntax

  1. SQL statements can be written in one or more lines and end with a semicolon . (Remember to add a semicolon!!!)
  2. SQL statements can use spaces/indentation to enhance the readability of the statement (the number of spaces and indentations does not matter).
  3. The SQL statements of the MySQL database are not case-sensitive, and it is recommended to use capital letters for keywords.
  4. Notes:
    • Single-line comment: ——comment content or #comment content (MySQL specific)
    • Multi-line comment: /*comment content*/

SQL classification

insert image description hereCorresponding to:
DDL: define the database, define the header (id, name), etc.
DML: add, delete and modify the data in the table
DQL: query the data in the table
DCL: create users, control user permissions


DDL

DDL - Database Operations

Query all databases:

SHOW DATABASES;

Query the current database:

SELECT DATABASE();remember to add()

Create a database:

CREATE DATABASE [ IF NOT EXISTS ] 数据库名 [ DEFAULT CHARSET 字符集] [COLLATE 排序规则 ];
insert image description here
If the database name already exists, an error will be reported
insert image description hereto avoid error (plus if not exists):
insert image description here
add character set (utf8 in mysql can only support character encoding with a length of 3bytes at most, for some characters that need to occupy 4bytes, utf8 of mysql does not support it. Only use utf8mb4 )
insert image description here

Delete the database:

DROP DATABASE [ IF EXISTS ] 数据库名;
In the same way, using when deleting if existscan avoid reporting errors.
insert image description here

Use the database:

USE 数据库名;
It is used when switching the database used, without exiting, and switching directly.


DDL-table operations

create

Create table:

CREATE TABLE 表名(
	字段1 字段1类型 [COMMENT 字段1注释],
	字段2 字段2类型 [COMMENT 字段2注释],
	字段3 字段3类型 [COMMENT 字段3注释],
	...
	字段n 字段n类型 [COMMENT 字段n注释]
)[ COMMENT 表注释 ];

Enter the database used before creating, use use xxx.
insert image description here
The string type represented by varchar, because the gender is only male or female, so the length of the string is 1, that is, use varchar(1), the detailed data type will be introduced below.

Inquire

Query all tables in the current database:

SHOW TABLES;Need to enter the database used first, use use xxx.

Query table structure:

DESC 表名;
insert image description here

Query the table creation statement of the specified table:

SHOW CREATE TABLE 表名;
insert image description here

Revise

Add fields:

ALTER TABLE 表名 ADD 字段名 类型(长度) [COMMENT 注释] [约束];
example:alter table user1 add idcard varchar(18) comment '身份证号';
insert image description here

Modify the data type of the field:

ALTER TABLE 表名 MODIFY 字段名 新数据类型(长度);
For example:alter table user1 modify name varchar(20);
insert image description here

Modify the field name and field type:

ALTER TABLE 表名 CHANGE 旧字段名 新字段名 类型(长度) [COMMENT 注释] [约束];
example:alter table user1 change id ip varchar(16);
insert image description here

Delete field:

ALTER TABLE 表名 DROP 字段名;

Modify the table name:

ALTER TABLE 表名 RENAME [TO/AS] 新表名;
insert image description here

drop table:

DROP TABLE [IF EXISTS] 表名;

Empty the table's data (drop the table and recreate it)

It is to clear the data of the table, just drop it first and then create it, and only keep the table header:
TRUNCATE TABLE 表名;

insert image description here

DDL-data types and cases

value type

insert image description here
The signed range refers to the value range when negative numbers are allowed, and the signed data type is used by default when defining.
The unsigned range refers to the value range when negative numbers are not allowed, and it can be marked after the data type when used UNSIGNED.
The precision refers to the whole number length, and the scale refers to the fractional part length, for example, the precision of 123.45 is 5, and the scale is 2.

For example:

  1. When defining age, the range of age is about 0-200, and they are all integers. There are types that meet the requirements TINYINT、SMALLINT、MEDIUMINT、INT. In order to save space, we can use TINYINT, such as: age TINYINT UNSIGNED.
  2. When defining a fraction, the range is roughly –100.0-100.0, which is a decimal. The commonly used types are FLOAT and DOUBLE. You can also specify the length of the number and the number of decimal places when using it: , score DOUBLE(4,1)which means that the maximum allowed number is 4 (100.0), and the length of the decimal place is specified as 1.

string type

insert image description in
When using the top two, you must specify the maximum length of the stored string, char(10), varchar(10), and an error will be reported when the specified length is exceeded.
charIt is a fixed-length string. If the specified length is 10, even if your string length is less than 10, it will automatically use spaces to add the string length to 10. The performance of char is higher .
varcharIt is a variable-length string. The length of the incoming string data will automatically calculate the space occupied by the string, so the performance of varchar is poor .
For example:

  1. When defining the name, because the length of each person's name string is different, it is varcharbetter to use;
  2. When defining gender, because the strings such as male and female occupy the same length, it is charbetter to use it.

time date type

insert image description hereThe range to pay attention TIMESTAMPto is very small, so use it with caution according to the occasion.
For example:
when defining a birthday, only the year, month, and day are recorded, so use DATE.

the case

insert image description here

create table emp(
id int,
workno varchar(10) comment '工号',
name varchar(10) comment '姓名',
gender char(1) comment '性别',
age tinyint unsigned comment '年龄',
idcard char(18) comment '身份证号',
entrydate date comment '入职时间'
)comment '员工表';

insert image description here
2. Add a new field "nickname" to the table emp as nickname, and the type is varchar(20).
3. Change nickname to username, and the type is varchar(30).
4. Delete the field username.
insert image description here

Summarize

insert image description here


DML

DML - add data

Add fields to specified fields:

INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (值1, 值2, ...);

Add fields to all fields:

INSERT INTO 表名 VALUES (值1, 值2, ...);

Add data in batches:

INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (值1, 值2, ...), (值1, 值2, ...), (值1, 值2, ...);
INSERT INTO 表名 VALUES (值1, 值2, ...), (值1, 值2, ...), (值1, 值2, ...);

For example:

insert into emp values(3,'3','韦一笑','男',38,'123456789087654321','1975-01-01'),
                       (4,'4','赵敏','女',39,'123456789087654322','1975-05-01');

Precautions

  • When inserting data, the order of the specified fields needs to correspond to the order of the values ​​one by one. If adding all fields, you need to enter all the corresponding values, otherwise an error will be reported.
  • 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.

DML - modify data

UPDATE 表名 SET 字段名1 = 值1, 字段名2 = 值2, ... [ WHERE 条件 ];
For example:update emp set name='小昭',gender='女' where id=1;

Precautions

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

For example:update emp set entrydate='2008-01-01';
insert image description here

DML - delete data:

DELETE FROM 表名 [ WHERE 条件 ];
For example:delete from emp where gender='女';

Precautions

  • The condition of the DELETE statement may or may not be present. If there is no condition, all data in the entire table will be deleted.
  • The DELETE statement cannot delete the value of a certain field (you can use UPDATE to set the field value to NULL UPDATE 表名 set 字段=NULL WHERE ...).

Summarize

insert image description here

DQL

Before starting, rebuild the data table and upload some data, the code is as follows:

use study;

drop table if exists emp;

create table emp(
    id int comment '编号',
    workno varchar(10) comment '工号',
    name varchar(10) comment '姓名',
    gender char(1) comment '性别',
    age tinyint unsigned comment '年龄',
    idcard char(18) comment '身份证号',
    workaddress varchar(50) comment '工作地址',
    entrydate date comment '入职时间'
)comment '员工表';

insert into emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
values (1, '00001', '柳岩666', '女', 20, '123456789012345678', '北京', '2000-01-01'),
        (2, '00002', '张无忌', '男', 18, '123456789012345670', '北京', '2005-09-01'),
        (3, '00003', '韦一笑', '男', 38, '123456789712345670', '上海', '2005-08-01'),
        (4, '00004', '赵敏', '女', 18, '123456757123845670', '北京', '2009-12-01'),
        (5, '00005', '小昭', '女', 16, '123456769012345678', '上海', '2007-07-01'),
        (6, '00006', '杨逍', '男', 28, '12345678931234567X', '北京', '2006-01-01'),
        (7, '00007', '范瑶', '男', 40, '123456789212345670', '北京', '2005-05-01'),
        (8, '00008', '黛绮丝', '女', 38, '123456157123645670', '天津', '2015-05-01'),
        (9, '00009', '范凉凉', '女', 45, '123156789012345678', '北京', '2010-04-01'),
        (10, '00010', '陈友谅', '男', 53, '123456789012345670', '上海', '2011-01-01'),
        (11, '00011', '张士诚', '男', 55, '123567897123465670', '江苏', '2015-05-01'),
        (12, '00012', '常遇春', '男', 32, '123446757152345670', '北京', '2004-02-01'),
        (13, '00013', '张三丰', '男', 88, '123656789012345678', '江苏', '2020-11-01'),
        (14, '00014', '灭绝', '女', 65, '123456719012345670', '西安', '2019-05-01'),
        (15, '00015', '胡青牛', '男', 70, '12345674971234567X', '西安', '2018-04-01'),
        (16, '00016', '周芷若', '女', 18, null, '北京', '2012-06-01') ;

DQL-Basic query

Query multiple fields

SELECT 字段1, 字段2, 字段3, ... FROM 表名;
For example:select id,name,idcard from emp;
insert image description here

SELECT * FROM 表名;
For example: select * from emp;try not to use * in actual development, one is not intuitive, and the other is that the efficiency is too low when there are too many data.
insert image description here

set alias

SELECT 字段1 [ AS 别名1 ], 字段2 [ AS 别名2 ], 字段3 [ AS 别名3 ], ... FROM 表名;
SELECT 字段1 [ 别名1 ], 字段2 [ 别名2 ], 字段3 [ 别名3 ], ... FROM 表名;
For example: select workaddress as '工作地址' from emp;/select workaddress '工作地址' from emp;
insert image description here

Remove duplicate records

SELECT DISTINCT 字段列表 FROM 表名;
For example:select distinct workaddress '工作地址' from emp;
insert image description here

escape

SELECT * FROM emp WHERE name LIKE '柳岩___';
SELECT * FROM 表名 WHERE name LIKE '柳岩/___' ESCAPE '/'
The _ after / is not a wildcard

DQL-Conditional query

grammar:

SELECT 字段列表 FROM 表名 WHERE 条件列表;

Conditions/operators:

comparison operator Function
> more than the
>= greater or equal to
< less than
<= less than or equal to
= equal
<> or != not equal to
BETWEEN … AND … Within a certain range (including minimum and maximum values)
IN(…) The value in the list after in, choose one more
LIKE placeholder Fuzzy matching (_ matches a single character, % matches any character)
IS NULL is NULL
Logical Operators Function
AND 或 && And (Multiple conditions are true at the same time)
OR 或 || or (any one of multiple conditions is true)
NOT or ! no, no

the case

  • Query employees whose age is equal to 88
    select * from emp where age = 88;
  • Query employee information whose age is less than or equal to 20
    select * from emp where age <= 20;
  • To query employee information without an ID card number,
    select * from emp where idcard is null;you cannot use idcard=null to judge, because null means that there is no such data, so it cannot be compared.
  • Query employee information with ID number
    select * from emp where idcard is not null;
  • Query employee information whose age is not equal to 88
    select * from emp where age != 88;
    select * from emp where age <> 88;
    select * from emp where not age=88;
  • Query the employee information whose age is between 15 (inclusive) and 20 (inclusive) You
    select * from emp where age >= 15 && age <= 20;
    select * from emp where age >= 15 and age <= 20;
    select * from emp where age between 15 and 20;must first write the minimum value and then the maximum value
  • Query the information of employees who are female and younger than 25 years old
    select * from emp where gender = '女' and age < 25;
  • Query employee information whose age is equal to 18 or 20 or 40
    select * from emp where age = 18 or age = 20 or age =40;
    select * from emp where age in(18,20,40);
  • Query employee information with two-character names_ %
    select * from emp where name like '__';
  • Query the employee information whose ID number is X at the end
    select * from emp where idcard like '%X';
    select * from emp where idcard like '_________________X';

DQL - aggregate functions

Common aggregate functions

function Function
count total number
max maximum value
min minimum value
avg average value
sum to sum

grammar

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

the case

  • Count the number of employees of the company
    select count(*) from emp; -- 统计的是总记录数 ,相当于查行数
    select count(idcard) from emp; -- 统计的是idcard字段不为null的记录数
  • For the count aggregation function, the total number of records that meet the conditions can be counted, and statistical queries can also be performed in the form of count (number/string)
    , such as:select count(1) from emp;
  • Calculate the average age of the company's employees
    select avg(age) from emp;
  • Count the maximum age of the company's employees
    select max(age) from emp;
  • Statistics of the minimum age of employees of this enterprise
    select min(age) from emp;
  • Count the sum of the ages of employees in Xi'an
    select sum(age) from emp where workaddress = '西安';

Notice

NULL values ​​are not calculated during aggregation queries. For example, when calculating the average age, the divisor is the number of rows except for ages that are NULL values.

DQL-group query

grammar

SELECT 字段列表 FROM 表名 [ WHERE 条件 ] GROUP BY 分组字段名 [ HAVING 分组后的过滤条件 ];

The difference between whereand 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, but the field judged after having must appear in the field after group by .

Notice

  • After grouping, the fields to be queried are generally aggregation functions and grouping fields , and it is meaningless to query other fields.
  • In the new version, when a grouping statement is used, other column names cannot be included in the select query list , unless the column also appears in the group clause, but aggregate functions can use other column names.
  • Execution order: where > aggregate function > having .
  • Support multi-field grouping, the specific syntax is: group by columnA,columnB

the case

  • According to gender grouping, counting the number of male employees and female employees
    select gender,count(*) from emp group by gender;group by is equivalent to aggregating the table into two groups, and then count(*) is to aggregate and query the numbers of the two groups and return them.
  • According to gender grouping, statistics of the average age of male employees and female employees
    select gender,avg(age) from emp group by gender;
  • Query the employees whose age is less than 45, and group them according to the work address, get the work address with the number of employees greater than or equal to 3
    select workaddress as '工作地',count(*) from emp where age<45 group by workaddress having count(*)>=3;
    or
    select workaddress as '工作地',count(*) as num_count from emp where age<45 group by workaddress having num_count>=3;
    expand it: select workaddress as '工作地',count(*) from emp where age<45 group by '工作地' having count(*)>=3;it will report an error, the meaning of this line of code is that we want to use the alias of workaddress 'work place' to group by, mysql is in During parsing, aliases will be replaced during grouping ( parsing order of DQL grammar ) , so aliases cannot be used before this (only output can be displayed).
  • Count the number of male and female employees working at each work address
    select workaddress,gender,count(*) from emp group by workaddress,gender;

DQL - sort query

grammar

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

sort by

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

Precautions

  • If it is in ascending order, you can not specify the sorting method ASC;
  • If it is multi-field sorting, when the first field has the same value, it will be sorted according to the second field.

the case

  • Sort a company's employees in ascending order by age
    select * from emp order by age;
  • Sort the employees in descending order according to the entry time
    select * from emp order by entrydate desc;
  • Sort the company's employees in ascending order according to age, and then sort them in descending order according to the time of entry
    select * from emp order by gender, entrydate desc;

DQL-Paging query

grammar

SELECT 字段列表 FROM 表名 LIMIT 起始索引, 查询记录数 ;

Precautions

  • The starting index starts from 0, starting index = (query page number - 1) * number of records displayed on each page.
  • LIMIT is executed at the end of all grammars, it only intercepts the data and does not perform any other processing on the data.
  • Pagination query is a database dialect, and different databases have different implementations. In MySQL, it is LIMIT.
  • If the first page of data is being queried, the starting index can be omitted, which can be abbreviated as limit 10.

the case

  • Query employee data on page 1, display 10 records per page
    select * from emp limit 0, 10;orselect * from emp limit 10;
  • Query the employee data on page 2, display 10 records per page --------> (page number-1)*number of records displayed on page
    select * from emp limit 10, 10;

Writing order of DQL grammar

SELECT
	字段列表
FROM
	表名字段
WHERE
	条件列表
GROUP BY
	分组字段列表
HAVING
	分组后的条件列表
ORDER BY
	排序字段列表
LIMIT
	分页参数

Execution order of DQL syntax

1.FROM
2.ON
3.JOIN
4.WHERE
5.GROUP BY
6.WITH CUBE 或 WITH ROLLUP
7.HAVING
8.SELECT
9.DISTINCT
10.ORDER BY
11.LIMIT

the case

  • We give the emp table an alias e, and then use the alias in select and where.
    select e.name , e.age from emp e where e.age > 15 order by age asc;, you can see that from is executed first.

Note that if an alias is defined at the time of from, the subsequent operations are all based on this 'virtual table', so only this alias can be used instead of the original table name.
However, if an alias is defined locally for a field after from, then the original field name and alias can be used because this table has already been imported.

Parsing order of DQL syntax

1.FROM 子句 组装来自不同数据源的数据
2.WHERE 子句 基于指定的条件对记录进行筛选
3.GROUP BY 子句 将数据划分为多个分组(划分时会解析as来形成别名,从而形成“虚拟表”,后面解析时便可以使用别名或者原名)
4.使用聚合函数对所有分组进行计算
5.使用HAVING子句筛选分组
6.计算所有的表达式
7.使用ORDER BY对结果集进行排序

the case

For 3, a verification can be given.
select workaddress as '工作地',count('工作地') as acount from emp;
select workaddress as '工作地',count('工作地') as acount from emp group by workaddress;
The difference lies in whether there is a group by. The above one will report an error because the alias is not recognized, and the following one can run normally.

DQL-Case Exercise

  1. Query information about employees aged 20, 21, 22, and 23.
    select * from emp where gender = '女' and age in (20,21,22,23);
  2. Query employees whose gender is male and whose name is three characters and whose age is between 20 and 40 years old (inclusive).
    select * from emp where gender = '男' and (age between 20 and 40) and (name like '___');
  3. Count the number of male employees and female employees who are younger than 60 years old in the employee table.
    select gender, count(*) from emp where age<60 group by gender;
  4. Query the name and age of all employees whose age is less than or equal to 35, and sort the query results in ascending order of age, and sort in descending order of entry time if the age is the same.
    select name, age from emp where age<=35 order by age asc, entrydate desc;
  5. Query the information of the first 5 employees whose gender is male and whose age is within 20-40 years old (inclusive), the query results are sorted in ascending order of age, and those of the same age are sorted in ascending order of entry time.
    select * from emp where gender = '男' and age between 20 and 40 order by age asc , entrydate asc limit 5;

DCL

DCL management user

Query users

select * from mysql.user; or
use mysql; select * from user;

User information is stored in the user table of the mysql database, so it is enough to query the table.
insert image description hereAmong them, Host represents the host accessed by the current user. If it is localhost, it only means that it can only be accessed on the current local machine, and
remote access is not allowed. User represents the user name to access the database. In MySQL, a
user needs to be uniquely identified by Host and User.

create user

CREATE USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '密码';

Modify user password

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

delete users

DROP USER '用户名'@'主机名' ;

Notice

  • In MySQL, a user needs to be uniquely identified by username@hostname.
  • Hostnames can use % wildcards.
  • This type of SQL developers operate less, mainly
    used by DBA (Database Administrator database administrator).

the case

  • Create a user itcast, which can only be accessed on the current host localhost, with a password of 123456;
    create user 'itcast'@'localhost' identified by '123456';
    insert image description here
    re-use this user to view the database on the command line, and you can find that only two databases are displayed, because no permissions have been assigned to him.insert image description here

  • Create user god, who can access the database on any host, password 123456;
    create user 'god'@'%' identified by '123456';

  • Modify the access password of user god to 1234;
    alter user 'god'@'%' identified with mysql_native_password by '1234';(mysql_native_password is an encryption method, which can also be specified when creating a user. The client should use the encryption method mysql_native_password. Caching_sha2_password is newly introduced by mysql8.0, just pay attention)

  • delete itcast@localhost user
    drop user 'itcast'@'localhost';

DCL permission control

Common permissions:

permissions illustrate
ALL, ALL PRIVILEGES all permissions
SELECT Query data
INSERT insert data
UPDATE change the data
DELETE delete data
ALTER modify table
DROP drop database/table/view
CREATE Create database/table

The above is just a brief list of several common permission descriptions. For other permission descriptions and their meanings, you can directly refer to the official documents

Query permission

SHOW GRANTS FOR '用户名'@'主机名' ;

Granted permission

GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'主机名';

revoke permission

REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'主机名';

Notice

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

the case

  • Query the permissions of the 'god'@'%' user
    show grants for 'god'@'%';
  • Grant 'god'@'%' user all operation permissions of all tables in mysql database
    grant all on mysql.* to 'god'@'%';
  • Revoke all privileges on the itcast database for user 'god'@'%'
    rrevoke all on study.* from 'god'@'%';(superuser)

Guess you like

Origin blog.csdn.net/qq_49030008/article/details/126613650