Introduction to mysql basics day1 power node [Old Du] class notes

day_1

The original author of this article is the lecture notes written by Mr. Du, the teaching director of Power Node, in his class Lao Du takes you to learn_mysql basics (mysql basic video + database combat)

See the link at the end of the document for the document and its related materials

After I downloaded the lecture notes txt, I converted it into markdown format, and adjusted some of the content, so I submitted it to the original area. If there is any infringement, it must be deleted

The text description below the original video is as follows:

This set of MySQL database video tutorials is narrated by Mr. Du, the teaching director of PowerNode. It explains the relevant knowledge of MySQL in detail, including MySQL overview, MySQL application environment, MySQL system characteristics, MySQL basics, MySQL management tools, how to install MySQL and MySQL New features, you can master the full set of MySQL knowledge by watching this set of Java video tutorials

1. What is a database? What is a Database Management System? What is SQL? What is the relationship between them?

1.1. Database

The English word DataBase, referred to as DB. A combination of files that store data in a certain format. As the name suggests: the warehouse for storing data is actually a bunch of files. These files store data in a specific format.

1.2. Database management system

Data Base Management, referred to as DBMS. The database management system is specially used to manage the data in the database. The database management system can add, delete, modify and check the data in the database.

1.3. Common database management systems

MySQL、Oracle、MS SqlServer、DB2、sybase 等…

1.4. SQL: Structured Query Language

Programmers need to learn SQL statements. Programmers write SQL statements, and then DBMS is responsible for executing SQL
statements, and finally complete the addition, deletion, modification and query of data in the database.

SQL is a set of standards. Programmers mainly learn SQL statements. This SQL can be used in mysql, Oracle, and DB2.

The relationship between the three? DBMS – Execution –> SQL --Operation –> DB

First install the database management system MySQL, and then learn how to write SQL statements. After writing SQL statements, the DBMS executes the SQL statements, and finally completes the data management of the database.

2. Install the MySQL database management system

Own Baidu! ! !

2.1. Matters needing attention?

2.1.1. Port number

The port number port is common to any software/application, and the port number is the only representative of the application. The port number is usually together with the IP address, the IP address is used to locate the computer, and the port number port is used to locate a certain service/application on the computer! On the same computer, the port number cannot be repeated. Unique.

When the mysql database is started, the default port number occupied by this service is 3306, which is known to everyone. remember.

2.1.2. Character encoding method

Set the character encoding of the mysql database to UTF8. Be sure to note: first select the 3rd radio button, and then select the utf8 character set.

2.1.3. Service name

The default is: MySQL does not need to be changed.

2.1.4. Choose to configure the environment variable path

What if there is no choice? You can manually configure
path=other paths;

Usually C:\Program Files (x86)\MySQL\MySQL Server\bin

2.1.5. Others

The username of the mysql super administrator cannot be changed, it must be: root, and you need to set the password of the mysql database super administrator. We set it to 123456.

While setting the password, you can activate the root account remote access. Activate: It means that the root account can log in from other places. Inactive: Indicates that the root account can only be used on this machine. I choose to activate here!

3. Perfect uninstallation of MySQL database

Step 1: Double-click the installation package to uninstall and delete it.

Step 2: Delete the directory: delete the MySQL directory under C:\ProgramData. Delete the MySQL directory under C:\Program Files (x86).

This completes the uninstallation!

4. I forgot my password

Own Baidu! ! !

5. In the windows operating system, how to use commands to start and stop the mysql service?

standard:

net stop 服务名称;
net start 服务名称;

Operation, mysql 8.0:

net stop mysql80;
net start mysql80;

The above commands can be used to start and stop other services.

6. Mysql is installed and the service is started. How to use the client to log in to the mysql database?

Use the mysql.exe command in the bin directory to connect to the mysql database server

6.1. Local login (display password writing form)

mysql -uroot -p123456

6.2. Local login (in the form of hidden password)

mysql -uroot -p
Enter password: ******

7. Mysql common commands

Note: The following commands are case-insensitive and all will work.

Note: End with a semicolon, which is the English semicolon.

Note: Mysql does not execute without ";", ";" means end!

mysql> show
->
->
-> \c
mysql>
\c用来终止一条命令的输入。

7.1. Exit mysql

exit

7.2. Check which databases exist in mysql?

show databases;

7.3. mysql comes with 4 databases by default

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+

7.4. How to choose a certain database?

Using a database called test:

mysql> use test;
Database changed

7.5. How to create a database?

mysql> create database bjpowernode;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| bjpowernode        |
| mysql              |
| performance_schema |
| test               |
+--------------------+

7.6. Check which tables exist in a certain database?

mysql> show tables;

7.7. View the version number of the mysql database

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.5.36    |
+-----------+

7.8. Check which database is currently in use?

mysql> select database();
+-------------+
| database()  |
+-------------+
| bjpowernode |
+-------------+

8. The most basic unit in the database is the table: table

What is a table table? Why use tables to store data?

姓名  性别  年龄(列:字段)
---------------------------
张三  男           20            ------->行(记录)
李四  女           21            ------->行(记录)
王五  男           22            ------->行(记录)

Databases represent data in the form of tables. Because the table is more intuitive.

Any table has rows and columns:

  • Line (row): known as data / records.
  • Column (column): is called a field.

Each field has attributes such as field name, data type, and constraints.

The field name is understandable, it is an ordinary name, just see the name and know the meaning.

Data types: strings, numbers, dates, etc., will be discussed later.

Constraints: There are also many constraints, one of which is called a unique constraint. After this constraint is added, the data in this field cannot be repeated.

9. About the classification of SQL statements

There are many SQL statements, it is best to classify them so that they are easier to remember. Divided into:

9.1. DQL: Data Query Language

Anything with the select keyword is a query statement

select...

9.2. DML: Data Manipulation Language

All additions, deletions and modifications to the data in the table are DML. This is mainly to manipulate the data in the table.

insert delete update
insertdeleteupdate

9.3. DDL: Data Definition Language

Anything with create, drop, alter is DDL. DDL mainly operates on the structure of tables. Not the data in the table.

create:新建,等同于增
drop:删除
alter:修改
这个增删改和 DML 不同,这个主要是对表结构进行操作。

9.4. TCL: Transaction Control Language

事务提交:commit;
事务回滚:rollback;

9.5. DCL

is the data control language. For example:

授权 grant、撤销权限 revoke....

10. Import the data prepared in advance

First, enter a database at will, which can be self-contained, preferably newly created by yourself

bjpowernode.sql This file is the database table I prepared for everyone's practice in advance.

How to import the data in the sql file?

mysql> source D:...\bjpowernode.sql

Note: Do not have Chinese in the path! ! ! !

11. About the imported tables

mysql> show tables;
+-----------------------+
| Tables_in_bjpowernode |
+-----------------------+
| dept                  |
| emp                   |
| salgrade              |
+-----------------------+

dept is the department table, emp is the employee table, and salgrade is the salary grade table

11.1. How to view the data in the table?

standard:

select * from 表名; //统一执行这个SQL语句。

operate:

mysql> select * from emp; // 从emp表查询所有数据。
+-------+--------+-----------+------+------------+---------+---------+--------+
| EMPNO | ENAME  | JOB       | MGR  | HIREDATE   | SAL     | COMM    | DEPTNO |
+-------+--------+-----------+------+------------+---------+---------+--------+
|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |
|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |
|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |
|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |
|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |
|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |
|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |
|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |
|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |
|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 |
|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |
|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |
|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |
|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |
+-------+--------+-----------+------+------------+---------+---------+--------+


mysql> select * from dept;
+--------+------------+----------+
| DEPTNO | DNAME      | LOC      |
+--------+------------+----------+
|     10 | ACCOUNTING | NEW YORK |
|     20 | RESEARCH   | DALLAS   |
|     30 | SALES      | CHICAGO  |
|     40 | OPERATIONS | BOSTON   |
+--------+------------+----------+

mysql> select * from salgrade;
+-------+-------+-------+
| GRADE | LOSAL | HISAL |
+-------+-------+-------+
|     1 |   700 |  1200 |
|     2 |  1201 |  1400 |
|     3 |  1401 |  2000 |
|     4 |  2001 |  3000 |
|     5 |  3001 |  9999 |
+-------+-------+-------+

12. Do not look at the data in the table, only look at the structure of the table, there is a command

standard:

desc 表名;

operate:

mysql> desc dept;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| DEPTNO | int(2)      | NO   | PRI | NULL    |       |部门编号
| DNAME  | varchar(14) | YES  |     | NULL    |       |部门名字
| LOC    | varchar(13) | YES  |     | NULL    |       |地理位置
+--------+-------------+------+-----+---------+-------+
mysql> desc emp;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| EMPNO    | int(4)      | NO   | PRI | NULL    |       |员工编号
| ENAME    | varchar(10) | YES  |     | NULL    |       |员工姓名
| JOB      | varchar(9)  | YES  |     | NULL    |       |工作岗位
| MGR      | int(4)      | YES  |     | NULL    |       |上级编号
| HIREDATE | date        | YES  |     | NULL    |       |入职日期
| SAL      | double(7,2) | YES  |     | NULL    |       |工资
| COMM     | double(7,2) | YES  |     | NULL    |       |补助
| DEPTNO   | int(2)      | YES  |     | NULL    |       |部门编号
+----------+-------------+------+-----+---------+-------+
mysql> desc salgrade;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| GRADE | int(11) | YES  |     | NULL    |       |工资等级
| LOSAL | int(11) | YES  |     | NULL    |       |最低工资
| HISAL | int(11) | YES  |     | NULL    |       |最高工资
+-------+---------+------+-----+---------+-------+

describe is abbreviated as: desc, you can use non-abbreviated

mysql> describe dept;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| DEPTNO | int(2)      | NO   | PRI | NULL    |       |
| DNAME  | varchar(14) | YES  |     | NULL    |       |
| LOC    | varchar(13) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+

13. Simple query

13.1. Querying a field

standard:

select 字段名 from 表名;

It should be noted that both select and from are keywords. Both field names and table names are identifiers. It is common for SQL statements, all SQL statements end with ";". In addition, the SQL statement is not case-sensitive, and it is fine.

Operation, query department name:

mysql> select dname from dept;
+------------+
| dname |
+------------+
| ACCOUNTING |
| RESEARCH |
| SALES |
| OPERATIONS |
+------------+
4 rows in set (0.00 sec)

mysql> SELECT DNAME FROM DEPT;
+------------+
| DNAME      |
+------------+
| ACCOUNTING |
| RESEARCH   |
| SALES      |
| OPERATIONS |
+------------+
4 rows in set (0.00 sec)

13.2. How to query two fields or multiple fields?

Use a comma to separate ","

Operation, query department number and department name:

select deptno,dname from dept;
+--------+------------+
| deptno | dname      |
+--------+------------+
|     10 | ACCOUNTING |
|     20 | RESEARCH   |
|     30 | SALES      |
|     40 | OPERATIONS |
+--------+------------+

13.3. How to query all fields?

13.3.1. Write each field

select a,b,c,d,e,f... from tablename;

13.3.2. Using *

select * from dept;
+--------+------------+----------+
| DEPTNO | DNAME      | LOC      |
+--------+------------+----------+
|     10 | ACCOUNTING | NEW YORK |
|     20 | RESEARCH   | DALLAS   |
|     30 | SALES      | CHICAGO  |
|     40 | OPERATIONS | BOSTON   |
+--------+------------+----------+

Disadvantages of this approach:

  • low efficiency
  • Poor readability.

It is not recommended in actual development, you can play by yourself no problem. You can use this method to quickly take a look at the entire table data in the DOS command window.

13.4. Aliasing columns in a query?

Use the as keyword for aliases.

mysql> select deptno,dname as deptname from dept;
+--------+------------+
| deptno | deptname   |
+--------+------------+
|     10 | ACCOUNTING |
|     20 | RESEARCH   |
|     30 | SALES      |
|     40 | OPERATIONS |
+--------+------------+

Note: Only the displayed query result column name is displayed as deptname, and the original table column name is still called: dname.

Remember: select statements are never modified. (Because it is only responsible for query)

Can the as keyword be omitted? OK

mysql> select deptno,dname deptname from dept;

Suppose there is a space in the alias when creating an alias, what should I do?

mysql> select deptno,dname dept name from dept;

When the DBMS sees such a statement, it compiles the SQL statement. If it does not conform to the syntax, an error is reported when compiling. How to deal with it?

select deptno,dname 'dept name' from dept; //加单引号
select deptno,dname "dept name" from dept; //加双引号
+--------+------------+
| deptno | dept name  |
+--------+------------+
|     10 | ACCOUNTING |
|     20 | RESEARCH   |
|     30 | SALES      |
|     40 | OPERATIONS |
+--------+------------+

Note: In all databases, single quotes are used to enclose strings uniformly. Single quotes are the standard, and double quotes cannot be used in oracle databases. But it can be used in mysql.

Emphasize again: the strings in the database are enclosed in single quotes. This is standard. Double quotes are not standard.

13.5. Calculate employee annual salary?

mysql> select ename,sal from emp;
+--------+---------+
| ename  | sal     |
+--------+---------+
| SMITH  |  800.00 |
| ALLEN  | 1600.00 |
| WARD   | 1250.00 |
| JONES  | 2975.00 |
| MARTIN | 1250.00 |
| BLAKE  | 2850.00 |
| CLARK  | 2450.00 |
| SCOTT  | 3000.00 |
| KING   | 5000.00 |
| TURNER | 1500.00 |
| ADAMS  | 1100.00 |
| JAMES  |  950.00 |
| FORD   | 3000.00 |
| MILLER | 1300.00 |
+--------+---------+
mysql> select ename,sal*12 from emp; // 结论:字段可以使用数学表达式!
+--------+----------+
| ename  | sal*12   |
+--------+----------+
| SMITH  |  9600.00 |
| ALLEN  | 19200.00 |
| WARD   | 15000.00 |
| JONES  | 35700.00 |
| MARTIN | 15000.00 |
| BLAKE  | 34200.00 |
| CLARK  | 29400.00 |
| SCOTT  | 36000.00 |
| KING   | 60000.00 |
| TURNER | 18000.00 |
| ADAMS  | 13200.00 |
| JAMES  | 11400.00 |
| FORD   | 36000.00 |
| MILLER | 15600.00 |
+--------+----------+

mysql> select ename,sal*12 as yearsal from emp; //起别名
+--------+----------+
| ename  | yearsal  |
+--------+----------+
| SMITH  |  9600.00 |
| ALLEN  | 19200.00 |
| WARD   | 15000.00 |
| JONES  | 35700.00 |
| MARTIN | 15000.00 |
| BLAKE  | 34200.00 |
| CLARK  | 29400.00 |
| SCOTT  | 36000.00 |
| KING   | 60000.00 |
| TURNER | 18000.00 |
| ADAMS  | 13200.00 |
| JAMES  | 11400.00 |
| FORD   | 36000.00 |
| MILLER | 15600.00 |
+--------+----------+

mysql> select ename,sal*12 as '年薪' from emp; //别名是中文,用单引号括起来。
+--------+----------+
| ename  | 年薪        |
+--------+----------+
| SMITH  |  9600.00 |
| ALLEN  | 19200.00 |
| WARD   | 15000.00 |
| JONES  | 35700.00 |
| MARTIN | 15000.00 |
| BLAKE  | 34200.00 |
| CLARK  | 29400.00 |
| SCOTT  | 36000.00 |
| KING   | 60000.00 |
| TURNER | 18000.00 |
| ADAMS  | 13200.00 |
| JAMES  | 11400.00 |
| FORD   | 36000.00 |
| MILLER | 15600.00 |
+--------+----------+

14. Conditional query

14.1. What is conditional query?

Not all the data in the table are checked out. It is found that it meets the conditions.

standard:

select
字段 1,字段 2,字段 3....
from
表名
where
条件;

14.2. What are the conditions?

14.2.1. = is equal to

Query the name and number of the employee whose salary is equal to 800?

select empno,ename from emp where sal = 800;

Inquire about SMITH's number and salary?

select empno,sal from emp where ename = 'SMITH'; //字符串使用单引号

14.2.2. <> or != not equal to

​ Query the names and numbers of employees whose salary is not equal to 800?
​ select empno,ename from emp where sal != 800;
​ select empno,ename from emp where sal <> 800; // an inequality sign consisting of a less than sign and a greater than sign

14.2.3. < less than

Query the names and numbers of employees whose salary is less than 2000?

mysql> select empno,ename,sal from emp where sal < 2000;
+-------+--------+---------+
| empno | ename  | sal     |
+-------+--------+---------+
|  7369 | SMITH  |  800.00 |
|  7499 | ALLEN  | 1600.00 |
|  7521 | WARD   | 1250.00 |
|  7654 | MARTIN | 1250.00 |
|  7844 | TURNER | 1500.00 |
|  7876 | ADAMS  | 1100.00 |
|  7900 | JAMES  |  950.00 |
|  7934 | MILLER | 1300.00 |
+-------+--------+---------+

14.2.4. <= less than or equal to

Query the names and numbers of employees whose salary is less than or equal to 3000?

select empno,ename,sal from emp where sal <= 3000;

14.2.5. > greater than

Query the names and numbers of employees whose salary is greater than 3000?

select empno,ename,sal from emp where sal > 3000;

14.2.6. >= greater than or equal to

Query the names and numbers of employees whose salary is greater than or equal to 3000?

select empno,ename,sal from emp where sal >= 3000;

14.2.7. between … and …. between two values, equivalent to >= and <=

Query employee information whose salary is between 2450 and 3000? Including 2450 and 3000

14.2.7.1. The first way: >= and <=

And is the meaning of and.

select empno,ename,sal from emp where sal >= 2450 and sal <= 3000;
+-------+-------+---------+
| empno | ename | sal     |
+-------+-------+---------+
|  7566 | JONES | 2975.00 |
|  7698 | BLAKE | 2850.00 |
|  7782 | CLARK | 2450.00 |
|  7788 | SCOTT | 3000.00 |
|  7902 | FORD  | 3000.00 |
+-------+-------+---------+
14.2.7.2. The second way: between … and …
select empno,ename,sal from emp where sal between 2450 and 3000;

Notice:

When using between and, you must follow the left small right big. between and is a closed interval, including the values ​​at both ends.

14.2.8. is null is null (is not null is not empty)

Query which employees have null allowances/subsidies?

mysql> select empno,ename,sal,comm from emp where comm = null;
Empty set (0.00 sec)

mysql> select empno,ename,sal,comm from emp where comm is null;
+-------+--------+---------+------+
| empno | ename  | sal     | comm |
+-------+--------+---------+------+
|  7369 | SMITH  |  800.00 | NULL |
|  7566 | JONES  | 2975.00 | NULL |
|  7698 | BLAKE  | 2850.00 | NULL |
|  7782 | CLARK  | 2450.00 | NULL |
|  7788 | SCOTT  | 3000.00 | NULL |
|  7839 | KING   | 5000.00 | NULL |
|  7876 | ADAMS  | 1100.00 | NULL |
|  7900 | JAMES  |  950.00 | NULL |
|  7902 | FORD   | 3000.00 | NULL |
|  7934 | MILLER | 1300.00 | NULL |
+-------+--------+---------+------+
10 rows in set (0.00 sec)

Note: Null cannot be measured using the equal sign in the database. You need to use is null because null in the database means nothing, it is not a value, so you cannot use the equal sign to measure.

Query which employees' allowances/subsidies are not null?

select empno,ename,sal,comm from emp where comm is not null;
+-------+--------+---------+---------+
| empno | ename  | sal     | comm    |
+-------+--------+---------+---------+
|  7499 | ALLEN  | 1600.00 |  300.00 |
|  7521 | WARD   | 1250.00 |  500.00 |
|  7654 | MARTIN | 1250.00 | 1400.00 |
|  7844 | TURNER | 1500.00 |    0.00 |
+-------+--------+---------+---------+

14.2.9. and

Query information about employees whose job title is MANAGER and whose salary is greater than 2500?

select empno,ename,job,sal from  emp where job = 'MANAGER' and sal > 2500;
+-------+-------+---------+---------+
| empno | ename | job     | sal     |
+-------+-------+---------+---------+
|  7566 | JONES | MANAGER | 2975.00 |
|  7698 | BLAKE | MANAGER | 2850.00 |
+-------+-------+---------+---------+

14.2.10. or or

Query jobs are employees of MANAGER and SALESMAN?

select empno,ename,job from emp where job = 'MANAGER';
select empno,ename,job from emp where job = 'SALESMAN';

select
empno,ename,job
from
emp
where
job = 'MANAGER' or job = 'SALESMAN';

+-------+--------+----------+
| empno | ename  | job      |
+-------+--------+----------+
|  7499 | ALLEN  | SALESMAN |
|  7521 | WARD   | SALESMAN |
|  7566 | JONES  | MANAGER  |
|  7654 | MARTIN | SALESMAN |
|  7698 | BLAKE  | MANAGER  |
|  7782 | CLARK  | MANAGER  |
|  7844 | TURNER | SALESMAN |
+-------+--------+----------+

14.2.11. If and and or appear at the same time, is there a priority problem?

Query the employees whose salary is greater than 2500 and whose department number is 10 or 20?

select
*
from
emp
where
sal > 2500 and deptno = 10 or deptno = 20;

Analyze the problem of the above sentence?

and has higher precedence than or. The above statement will first execute and, and then execute or.

What does the above statement mean?

Find out the employees whose salary is greater than 2500 and whose department number is 10, or find out all employees in 20 departments.

select
*
from
emp
where
sal > 2500 and (deptno = 10 or deptno = 20);

and and or appear at the same time, and the priority is higher. If you want or to be executed first, you need to add "parentheses". In future development, if you are not sure about the priority, just add parentheses.

14.2.12. in contains, equivalent to multiple or (not in is not in this range)

Query jobs are employees of MANAGER and SALESMAN?

select empno,ename,job from emp where job = 'MANAGER' or job = 'SALESMAN';
select empno,ename,job from emp where job in('MANAGER', 'SALESMAN');
+-------+--------+----------+
| empno | ename  | job      |
+-------+--------+----------+
|  7499 | ALLEN  | SALESMAN |
|  7521 | WARD   | SALESMAN |
|  7566 | JONES  | MANAGER  |
|  7654 | MARTIN | SALESMAN |
|  7698 | BLAKE  | MANAGER  |
|  7782 | CLARK  | MANAGER  |
|  7844 | TURNER | SALESMAN |
+-------+--------+----------+

Note: in is not a range. in followed by the specific value.

Query employee information whose salary is 800 and 5000?

select ename,sal from emp where sal = 800 or sal = 5000;
select ename,sal from emp where sal in(800, 5000); //这个不是表示800到5000都找出来。
+-------+---------+
| ename | sal     |
+-------+---------+
| SMITH |  800.00 |
| KING  | 5000.00 |
+-------+---------+
select ename,sal from emp where sal in(800, 5000, 3000);

// not in 表示不在这几个值当中的数据。
select ename,sal from emp where sal not in(800, 5000, 3000);
+--------+---------+
| ename  | sal     |
+--------+---------+
| ALLEN  | 1600.00 |
| WARD   | 1250.00 |
| JONES  | 2975.00 |
| MARTIN | 1250.00 |
| BLAKE  | 2850.00 |
| CLARK  | 2450.00 |
| TURNER | 1500.00 |
| ADAMS  | 1100.00 |
| JAMES  |  950.00 |
| MILLER | 1300.00 |
+--------+---------+

14.2.13. not is negation, mainly used in is or in

is null
is not null
in
not in

14.2.14. like

It is called fuzzy query and supports % or underscore matching. % is a special symbol, and _ is also a special symbol:

  • %: Match any number of characters
  • Underscore: any character

Find ones with an O in their name?

mysql> select ename from emp where ename like '%O%';
+-------+
| ename |
+-------+
| JONES |
| SCOTT |
| FORD  |
+-------+

Find names ending in T?

select ename from emp where ename like '%T';

Find names starting with K?

select ename from emp where ename like 'K%';

Find the second word of every A's?

select ename from emp where ename like '_A%';

Find out the third letter is R?

select ename from emp where ename like '__R%';

t_student student table

name字段
----------------------
zhangsan
lisi
wangwu
zhaoliu
jack_son

Spot the ones with "_" in their names?

select name from t_student where name like '%_%'; //这样不行。

mysql> select name from t_student where name like '%\_%'; // \转义字符。
+----------+
| name     |
+----------+
| jack_son |
+----------+

15. Sort

15.1. Query all employee salaries, sort?

select
ename,sal
from
emp
order by
sal; // 默认是升序!!!

+--------+---------+
| ename  | sal     |
+--------+---------+
| SMITH  |  800.00 |
| JAMES  |  950.00 |
| ADAMS  | 1100.00 |
| WARD   | 1250.00 |
| MARTIN | 1250.00 |
| MILLER | 1300.00 |
| TURNER | 1500.00 |
| ALLEN  | 1600.00 |
| CLARK  | 2450.00 |
| BLAKE  | 2850.00 |
| JONES  | 2975.00 |
| FORD   | 3000.00 |
| SCOTT  | 3000.00 |
| KING   | 5000.00 |
+--------+---------+

15.2. Designated descending order?

select
ename,sal
from
emp
order by
sal desc;

+--------+---------+
| ename  | sal     |
+--------+---------+
| KING   | 5000.00 |
| SCOTT  | 3000.00 |
| FORD   | 3000.00 |
| JONES  | 2975.00 |
| BLAKE  | 2850.00 |
| CLARK  | 2450.00 |
| ALLEN  | 1600.00 |
| TURNER | 1500.00 |
| MILLER | 1300.00 |
| MARTIN | 1250.00 |
| WARD   | 1250.00 |
| ADAMS  | 1100.00 |
| JAMES  |  950.00 |
| SMITH  |  800.00 |
+--------+---------+

15.3. Specify ascending order?

select
ename,sal
from
emp
order by
sal asc;

+--------+---------+
| ename  | sal     |
+--------+---------+
| SMITH  |  800.00 |
| JAMES  |  950.00 |
| ADAMS  | 1100.00 |
| WARD   | 1250.00 |
| MARTIN | 1250.00 |
| MILLER | 1300.00 |
| TURNER | 1500.00 |
| ALLEN  | 1600.00 |
| CLARK  | 2450.00 |
| BLAKE  | 2850.00 |
| JONES  | 2975.00 |
| FORD   | 3000.00 |
| SCOTT  | 3000.00 |
| KING   | 5000.00 |
+--------+---------+

15.4. Can two fields be sorted? Or sort by multiple fields?

Query the employee's name and salary, and ask for the ascending order of salary. If the salary is the same, then arrange in ascending order of name.

select
ename,sal
from
emp
order by
sal asc, ename asc; // sal 在前,起主导,只有 sal 相等的时候,才会考虑启用 ename 排序。

+--------+---------+
| ename  | sal     |
+--------+---------+
| SMITH  |  800.00 |
| JAMES  |  950.00 |
| ADAMS  | 1100.00 |
| MARTIN | 1250.00 |
| WARD   | 1250.00 |
| MILLER | 1300.00 |
| TURNER | 1500.00 |
| ALLEN  | 1600.00 |
| CLARK  | 2450.00 |
| BLAKE  | 2850.00 |
| JONES  | 2975.00 |
| FORD   | 3000.00 |
| SCOTT  | 3000.00 |
| KING   | 5000.00 |
+--------+---------+

15.5. Understanding: sorting is also possible according to the position of the field

select ename,sal from emp order by 2; // 2 表示第二列。第二列是 sal

Sort according to the second column sal of the query result.

To understand, it is not recommended to write this way in development, because it is not robust, and the order of columns is easy to change. After the order of columns is modified, the statement will be invalid.

16. A more comprehensive case

Find the employee information whose salary is between 1250 and 3000, and ask to sort them in descending order of salary.

select
ename,sal
from
emp
where
sal between 1250 and 3000
order by
sal desc;

+--------+---------+
| ename  | sal     |
+--------+---------+
| FORD   | 3000.00 |
| SCOTT  | 3000.00 |
| JONES  | 2975.00 |
| BLAKE  | 2850.00 |
| CLARK  | 2450.00 |
| ALLEN  | 1600.00 |
| TURNER | 1500.00 |
| MILLER | 1300.00 |
| MARTIN | 1250.00 |
| WARD   | 1250.00 |
+--------+---------+

Remember that the keyword order cannot be changed:

select
...
from
...
where
...
order by
...

The execution sequence of the above statements must be mastered:

  • The first step: from
  • The second step: where
  • The third step: select
  • Step 4: order by (sorting is always performed at the end!)

17. Data processing functions

17.1. Data processing functions are also called single row processing functions

The characteristics of a single-line processing function: one input corresponds to one output.

The opposite of single-line processing functions: multi-line processing functions. (Multi-line processing function features: multiple inputs, corresponding to 1 output!)

17.2. What are the common one-line processing functions?

17.2.1. lower Convert lowercase

mysql> select lower(ename) as ename from emp;
+--------+
| ename  |
+--------+
| smith  |
| allen  |
| ward   |
| jones  |
| martin |
| blake  |
| clark  |
| scott  |
| king   |
| turner |
| adams  |
| james  |
| ford   |
| miller |
+--------+

14 inputs and finally 14 outputs. This is characteristic of single-line processing functions.

17.2.2. upper Convert uppercase

mysql> select * from t_student;
+----------+
| name     |
+----------+
| zhangsan |
| lisi     |
| wangwu   |
| jack_son |
+----------+

mysql> select upper(name) as name from t_student;
+----------+
| name     |
+----------+
| ZHANGSAN |
| LISI     |
| WANGWU   |
| JACK_SON |
+----------+

17.2.3. substr get substring

substr(intercepted string, starting subscript, intercepted length)

select substr(ename, 1, 1) as ename from emp;

Note: The initial subscript starts from 1, there is no 0.
Find the employee information whose first letter is A?

  • The first way: fuzzy query
select ename from emp where ename like 'A%';
  • The second way: substr function
select
ename
from
emp
where
substr(ename,1,1) = 'A';

17.2.4. Capitalized first letter?

t_student student table

name字段
----------------------
zhangsan
lisi
wangwu
zhaoliu
jack_son
select name from t_student;
select upper(substr(name,1,1)) from t_student;
select substr(name,2,length(name) - 1) from t_student;
select concat(upper(substr(name,1,1)),substr(name,2,length(name) - 1)) as result from t_student;
+----------+
| result   |
+----------+
| Zhangsan |
| Lisi     |
| Wangwu   |
| Jack_son |
+----------+

17.2.5. Concat string concatenation

select concat(empno,ename) from emp;
+---------------------+
| concat(empno,ename) |
+---------------------+
| 7369SMITH           |
| 7499ALLEN           |
| 7521WARD            |
| 7566JONES           |
| 7654MARTIN          |
| 7698BLAKE           |
| 7782CLARK           |
| 7788SCOTT           |
| 7839KING            |
| 7844TURNER          |
| 7876ADAMS           |
| 7900JAMES           |
| 7902FORD            |
| 7934MILLER          |
+---------------------+

17.2.6. length get the length

select length(ename) enamelength from emp;
+-------------+
| enamelength |
+-------------+
|           5 |
|           5 |
|           4 |
|           5 |
|           6 |
|           5 |
|           5 |
|           5 |
|           4 |
|           6 |
|           5 |
|           5 |
|           4 |
|           6 |
+-------------+

17.2.7. trim remove spaces

mysql> select * from emp where ename = '  KING';
Empty set (0.00 sec)

mysql> select * from emp where ename = trim('   KING');
+-------+-------+-----------+------+------------+---------+------+--------+
| EMPNO | ENAME | JOB       | MGR  | HIREDATE   | SAL     | COMM | DEPTNO |
+-------+-------+-----------+------+------------+---------+------+--------+
|  7839 | KING  | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL |     10 |
+-------+-------+-----------+------+------------+---------+------+--------+

17.2.8. Date manipulation

Own Baidu! ! !

  • str_to_date converts a string to a date
  • date_format formatted date

17.2.9. format set thousandths

standard:

case..when..then..when..then..else..end

Operation, when the employee's job position is MANAGER, the salary is increased by 10%, when the job position is SALESMAN, the salary is increased by 50%, and the other is normal. (Note: The database is not modified, but the query result is displayed as a salary increase):

select
ename,
job,
sal as oldsal,
(case job when 'MANAGER' then sal*1.1 when 'SALESMAN' then sal*1.5 else sal end) as newsal
from
emp;

+--------+-----------+---------+---------+
| ename  | job       | oldsal  | newsal  |
+--------+-----------+---------+---------+
| SMITH  | CLERK     |  800.00 |  800.00 |
| ALLEN  | SALESMAN  | 1600.00 | 2400.00 |
| WARD   | SALESMAN  | 1250.00 | 1875.00 |
| JONES  | MANAGER   | 2975.00 | 3272.50 |
| MARTIN | SALESMAN  | 1250.00 | 1875.00 |
| BLAKE  | MANAGER   | 2850.00 | 3135.00 |
| CLARK  | MANAGER   | 2450.00 | 2695.00 |
| SCOTT  | ANALYST   | 3000.00 | 3000.00 |
| KING   | PRESIDENT | 5000.00 | 5000.00 |
| TURNER | SALESMAN  | 1500.00 | 2250.00 |
| ADAMS  | CLERK     | 1100.00 | 1100.00 |
| JAMES  | CLERK     |  950.00 |  950.00 |
| FORD   | ANALYST   | 3000.00 | 3000.00 |
| MILLER | CLERK     | 1300.00 | 1300.00 |
+--------+-----------+---------+---------+

17.2.10. round rounding

select 字段 from 表名;
select ename from emp;
select 'abc' from emp; // select后面直接跟“字面量/字面值”

mysql> select 'abc' as bieming from emp;
+---------+
| bieming |
+---------+
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
| abc     |
+---------+
mysql> select abc from emp;

ERROR 1054 (42S22): Unknown column 'abc' in 'field list'

This will definitely report an error, because abc will be regarded as the name of a field, and the abc field will be found in the emp table.

select 1000 as num from emp; // 1000 也是被当做一个字面量/字面值。
+------+
| num  |
+------+
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
| 1000 |
+------+

Conclusion: select can be followed by the field name of a table (which can be regarded as a variable name), or it can be followed by a literal value/literal value (data).

select 21000 as num from dept;
+-------+
| num   |
+-------+
| 21000 |
| 21000 |
| 21000 |
| 21000 |
+-------+

mysql> select round(1236.567, 0) as result from emp; //保留整数位。
+--------+
| result |
+--------+
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
|   1237 |
+--------+

select round(1236.567, 1) as result from emp; //保留1个小数
select round(1236.567, 2) as result from emp; //保留2个小数
select round(1236.567, -1) as result from emp; // 保留到十位。
+--------+
| result |
+--------+
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
|   1240 |
+--------+

select round(1236.567, -2) as result from emp;
+--------+
| result |
+--------+
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
|   1200 |
+--------+

17.2.11. rand() Generate random numbers

mysql> select round(rand()*100,0) from emp; // 100以内的随机数
+---------------------+
| round(rand()*100,0) |
+---------------------+
|                  76 |
|                  29 |
|                  15 |
|                  88 |
|                  95 |
|                   9 |
|                  63 |
|                  89 |
|                  54 |
|                   3 |
|                  54 |
|                  61 |
|                  42 |
|                  28 |
+---------------------+

17.2.12. ifnull converts null to a concrete value

ifnull is a null handling function. Specially handles empty ones. In all databases, as long as NULL participates in mathematical operations, the final result is NULL.

mysql> select ename, sal + comm as salcomm from emp;
+--------+---------+
| ename  | salcomm |
+--------+---------+
| SMITH  |    NULL |
| ALLEN  | 1900.00 |
| WARD   | 1750.00 |
| JONES  |    NULL |
| MARTIN | 2650.00 |
| BLAKE  |    NULL |
| CLARK  |    NULL |
| SCOTT  |    NULL |
| KING   |    NULL |
| TURNER | 1500.00 |
| ADAMS  |    NULL |
| JAMES  |    NULL |
| FORD   |    NULL |
| MILLER |    NULL |
+--------+---------+

Calculate the annual salary of each employee? Annual salary = (monthly salary + monthly subsidy) * 12

select ename, (sal + comm) * 12 as yearsal from emp;
+--------+----------+
| ename  | yearsal  |
+--------+----------+
| SMITH  |     NULL |
| ALLEN  | 22800.00 |
| WARD   | 21000.00 |
| JONES  |     NULL |
| MARTIN | 31800.00 |
| BLAKE  |     NULL |
| CLARK  |     NULL |
| SCOTT  |     NULL |
| KING   |     NULL |
| TURNER | 18000.00 |
| ADAMS  |     NULL |
| JAMES  |     NULL |
| FORD   |     NULL |
| MILLER |     NULL |
+--------+----------+

Note: As long as NULL participates in the operation, the final result must be NULL. In order to avoid this phenomenon, you need to use the ifnull function.

ifnull function usage: ifnull (data, which value is taken as)

If "data" is NULL, take this data structure as which value.

When subsidy is NULL, treat subsidy as 0

select ename, (sal + ifnull(comm, 0)) * 12 as yearsal from emp;
+--------+----------+
| ename  | yearsal  |
+--------+----------+
| SMITH  |  9600.00 |
| ALLEN  | 22800.00 |
| WARD   | 21000.00 |
| JONES  | 35700.00 |
| MARTIN | 31800.00 |
| BLAKE  | 34200.00 |
| CLARK  | 29400.00 |
| SCOTT  | 36000.00 |
| KING   | 60000.00 |
| TURNER | 18000.00 |
| ADAMS  | 13200.00 |
| JAMES  | 11400.00 |
| FORD   | 36000.00 |
| MILLER | 15600.00 |
+--------+----------+

18. Grouping function (multi-line processing function)

The characteristics of multi-line processing functions: input multiple lines, and finally output one line. 5 commonly used:

  • count count
  • sum
  • avg average value
  • max maximum value
  • min minimum value

Notice:

Grouping functions must be grouped before they can be used. If you do not group the data, the entire table defaults to one group.

Find out the highest salary?

mysql> select max(sal) from emp;
+----------+
| max(sal) |
+----------+
|  5000.00 |
+----------+

Find out minimum wage?

mysql> select min(sal) from emp;
+----------+
| min(sal) |
+----------+
|   800.00 |
+----------+

Calculate salary and:

mysql> select sum(sal) from emp;
+----------+
| sum(sal) |
+----------+
| 29025.00 |
+----------+

Calculate the average salary:

mysql> select avg(sal) from emp;
+-------------+
| avg(sal)    |
+-------------+
| 2073.214286 |
+-------------+

Add up all 14 salaries and divide by 14.

Count the number of employees?

mysql> select count(ename) from emp;
+--------------+
| count(ename) |
+--------------+
|           14 |
+--------------+

18.1. What should be paid attention to when using the grouping function?

18.1.1. The first point: the grouping function automatically ignores NULL, you don't need to deal with NULL in advance

mysql> select sum(comm) from emp;
+-----------+
| sum(comm) |
+-----------+
|   2200.00 |
+-----------+

mysql> select count(comm) from emp;
+-------------+
| count(comm) |
+-------------+
|           4 |
+-------------+
mysql> select avg(comm) from emp;
+------------+
| avg(comm)  |
+------------+
| 550.000000 |
+------------+

18.1.2. The second point: What is the difference between count(*) and count (specific fields) in the grouping function?

mysql> select count(*) from emp;
+----------+
| count(*) |
+----------+
|       14 |
+----------+

mysql> select count(comm) from emp;
+-------------+
| count(comm) |
+-------------+
|           4 |
+-------------+

count (specific field): indicates the total number of all elements that are not NULL under this field

count(*): The total number of rows in the statistics table. (As long as there is a row of data count, then ++)

If one column in a row of data is not NULL, the row of data is valid.

18.1.3. The third point: the grouping function cannot be used directly in the where clause

Find information about employees who are paid more than the minimum wage.

select ename,sal from emp where sal > min(sal);

There is no problem on the surface, run it?

ERROR 1111 (HY000): Invalid use of group function

After talking about group by query (group by), I will understand.

18.1.4. The fourth point: All grouping functions can be combined and used together

select sum(sal),min(sal),max(sal),avg(sal),count(*) from emp;
+----------+----------+----------+-------------+----------+
| sum(sal) | min(sal) | max(sal) | avg(sal)    | count(*) |
+----------+----------+----------+-------------+----------+
| 29025.00 |   800.00 |  5000.00 | 2073.214286 |       14 |
+----------+----------+----------+-------------+----------+

19. Group query (very important: five stars*****)

19.1. What is group query?

In practical applications, there may be such a requirement that it is necessary to group the data first, and then operate on the data of each group. At this time we need to use group query, how to perform group query?

standard:

select
...
from
...
group by
...

Try it yourself:

  • Calculate the salary sum of each department?
  • Calculate the average salary for each job?
  • Find out the highest salary for each job?

19.2. Combine all the previous keywords together to see their execution order?

select
...
from
...
where
...
group by
...
order by
...

The order of the above keywords cannot be reversed and needs to be memorized.

What is the order of execution?

  • from
  • where
  • group by
  • select
  • order by

Why can't the grouping function be used directly behind where?

select ename,sal from emp where sal > min(sal);//报错。

Because the grouping function must be grouped before it can be used.

When where is executed, there is no grouping yet. So the grouping function cannot appear after where.

select sum(sal) from emp;

This is not grouped, why can the sum() function be used? Because select is executed after group by.

19.3. Find the salary and ?

Implementation idea: group by job position, and then sum the wages.

select
job,sum(sal)
from
emp
group by
job;

+-----------+----------+
| job       | sum(sal) |
+-----------+----------+
| ANALYST   |  6000.00 |
| CLERK     |  4150.00 |
| MANAGER   |  8275.00 |
| PRESIDENT |  5000.00 |
| SALESMAN  |  5600.00 |
+-----------+----------+

What is the order of execution of the above statement?

First query data from the emp table. Group by job field. Then sum(sal) the data of each group

select ename,job,sum(sal) from emp group by job;
+-------+-----------+----------+
| ename | job       | sum(sal) |
+-------+-----------+----------+
| SCOTT | ANALYST   |  6000.00 |
| SMITH | CLERK     |  4150.00 |
| JONES | MANAGER   |  8275.00 |
| KING  | PRESIDENT |  5000.00 |
| ALLEN | SALESMAN  |  5600.00 |
+-------+-----------+----------+

The above statement can be executed in mysql, but it is meaningless. The above statement is executed in oracle and reports an error. The syntax of oracle is stricter than that of mysql. (The syntax of mysql is relatively loose!)

19.4. Key conclusions

In a select statement, if there is a group by statement, the select can only be followed by: the fields participating in the grouping, and the grouping function. All others cannot follow.

19.5. Find the highest salary for each department

What is the realization idea?

Group by department number and find the maximum value of each group.

It is meaningless to add the ename field after select, and oracle will report an error.

mysql> select ename,deptno,max(sal) from emp group by deptno;
+-------+--------+----------+
| ename | deptno | max(sal) |
+-------+--------+----------+
| CLARK |     10 |  5000.00 |
| SMITH |     20 |  3000.00 |
| ALLEN |     30 |  2850.00 |
+-------+--------+----------+

mysql> select deptno,max(sal) from emp group by deptno;
+--------+----------+
| deptno | max(sal) |
+--------+----------+
|     10 |  5000.00 |
|     20 |  3000.00 |
|     30 |  2850.00 |
+--------+----------+

19.6. Find the highest salary for each department and job?

+--------+-----------+---------+--------+
| ename  | job       | sal     | deptno |
+--------+-----------+---------+--------+
| MILLER | CLERK     | 1300.00 |     10 |
| KING   | PRESIDENT | 5000.00 |     10 |
| CLARK  | MANAGER   | 2450.00 |     10 |

| FORD   | ANALYST   | 3000.00 |     20 |
| ADAMS  | CLERK     | 1100.00 |     20 |
| SCOTT  | ANALYST   | 3000.00 |     20 |
| JONES  | MANAGER   | 2975.00 |     20 |
| SMITH  | CLERK     |  800.00 |     20 |

| BLAKE  | MANAGER   | 2850.00 |     30 |
| MARTIN | SALESMAN  | 1250.00 |     30 |
| ALLEN  | SALESMAN  | 1600.00 |     30 |
| TURNER | SALESMAN  | 1500.00 |     30 |
| WARD   | SALESMAN  | 1250.00 |     30 |
| JAMES  | CLERK     |  950.00 |     30 |
+--------+-----------+---------+--------+

Tip: Combine two fields into one field. (joint grouping of two fields)

select
deptno, job, max(sal)
from
emp
group by
deptno, job;

+--------+-----------+----------+
| deptno | job       | max(sal) |
+--------+-----------+----------+
|     10 | CLERK     |  1300.00 |
|     10 | MANAGER   |  2450.00 |
|     10 | PRESIDENT |  5000.00 |
|     20 | ANALYST   |  3000.00 |
|     20 | CLERK     |  1100.00 |
|     20 | MANAGER   |  2975.00 |
|     30 | CLERK     |   950.00 |
|     30 | MANAGER   |  2850.00 |
|     30 | SALESMAN  |  1600.00 |
+--------+-----------+----------+

19.7. Using having can further filter the data after grouping

having cannot be used alone, and having cannot replace where, and having must be used in conjunction with group by.

Find out the maximum salary of each department, and ask to display the maximum salary greater than 3000?

Step 1: Find the highest salary of each department, group by department number, and find the maximum value of each group.

select deptno,max(sal) from emp group by deptno;
+--------+----------+
| deptno | max(sal) |
+--------+----------+
|     10 |  5000.00 |
|     20 |  3000.00 |
|     30 |  2850.00 |
+--------+----------+

Step 2: Request to display the maximum salary is greater than 3000

select deptno,max(sal) from emp group by deptno
having
max(sal) > 3000;

+--------+----------+
| deptno | max(sal) |
+--------+----------+
|     10 |  5000.00 |
+--------+----------+

Think about a question: Is the execution efficiency of the above sql statement low?

It is relatively low. In fact, it can be considered as follows: first find out all the values ​​greater than 3000, and then group them.

select
deptno,max(sal)
from
emp
where
sal > 3000
group by
deptno;

+--------+----------+
| deptno | max(sal) |
+--------+----------+
|     10 |  5000.00 |
+--------+----------+

Optimization Strategy:

Where and having, where is the first choice, and where is really impossible to complete, then choose having.

19.8. where there is no way

Find out the average salary of each department, and ask to display the average salary higher than 2500

Step 1: Find out the average salary for each department

select deptno,avg(sal) from emp group by deptno;
+--------+-------------+
| deptno | avg(sal)    |
+--------+-------------+
|     10 | 2916.666667 |
|     20 | 2175.000000 |
|     30 | 1566.666667 |
+--------+-------------+

Step 2: Request to show those whose average salary is higher than 2500

select deptno,avg(sal) from emp group by deptno
having
avg(sal) > 2500;

+--------+-------------+
| deptno | avg(sal)    |
+--------+-------------+
|     10 | 2916.666667 |
+--------+-------------+

20. Big summary (single table query is over)

select
...
from
...
where
...
group by
...
having
...
order by
...

The above keywords can only be used in this order, not reversed.

20.1. Execution order?

  • from
  • where
  • group by
  • having
  • select
  • order by

To query data from a certain table, first pass the where condition to filter out valuable data. Group these valuable data by group by. After grouping, you can use having to continue filtering. select query out. Finally sort the output order by!

Find out the average salary of each position, request to display the average salary greater than 1500, except for the MANAGER position, and finally ask to sort in descending order of the average salary.

select
job, avg(sal) as avgsal
from
emp
where
job <> 'MANAGER'
group by
job
having
avg(sal) > 1500
order by
avgsal desc;

+-----------+-------------+
| job       | avgsal      |
+-----------+-------------+
| PRESIDENT | 5000.000000 |
| ANALYST   | 3000.000000 |
+-----------+-------------+

21. Download

21.1. This document

https://hty.ink/down/mysql/day_1.zip

21.2. Data involved

https://hty.ink/down/mysql/ziliao.zip

22. Continue reading

22.1. Next

https://hty.ink/2293/

Guess you like

Origin blog.csdn.net/weixin_45756789/article/details/124991464