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

day_2

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. Remove duplicate records from query results [distinct]

Note: The original table data will not be modified, only the query results will be deduplicated. Deduplication needs to use a keyword: distinct

mysql> select distinct job from emp;
+-----------+
| job       |
+-----------+
| CLERK     |
| SALESMAN  |
| MANAGER   |
| ANALYST   |
| PRESIDENT |
+-----------+

// 这样编写是错误的,语法错误。
// distinct只能出现在所有字段的最前方。
mysql> select ename,distinct job from emp;

// distinct出现在job,deptno两个字段之前,表示两个字段联合起来去重。
mysql> select distinct job,deptno from emp;
+-----------+--------+
| job       | deptno |
+-----------+--------+
| CLERK     |     20 |
| SALESMAN  |     30 |
| MANAGER   |     20 |
| MANAGER   |     30 |
| MANAGER   |     10 |
| ANALYST   |     20 |
| PRESIDENT |     10 |
| CLERK     |     30 |
| CLERK     |     10 |
+-----------+--------+

Count the number of jobs?

select count(distinct job) from emp;
+---------------------+
| count(distinct job) |
+---------------------+
|                   5 |
+---------------------+

2. Connection query

2.1. What is a join query?

A separate query from one table is called a single-table query.

The emp table and the dept table are combined to query data, the employee name is taken from the emp table, and the department name is taken from the dept table. This cross-table query, where multiple tables are combined to query data, is called a join query.

2.2. Classification of join queries?

2.2.1. Chronological classification according to grammar

  • SQL92: Syntax as it appeared in 1992
  • SQL99: Syntax as it appeared in 1999

Here we focus on learning SQL99, and briefly demonstrate an example of SQL92 in this process

2.2.2. Classification according to the way tables are joined

  • inner join
  • equijoin
  • non-equivalence join
  • self-join

2.2.3. Outer joins

  • left outer join (left join)
  • right outer join (right join)

2.2.4. Full connection (not to mention)

2.3. When two tables are connected and queried, what happens without any restrictions?

Case: Query the department name of each employee?

mysql> select ename,deptno from emp;
+--------+--------+
| ename  | deptno |
+--------+--------+
| SMITH  |     20 |
| ALLEN  |     30 |
| WARD   |     30 |
| JONES  |     20 |
| MARTIN |     30 |
| BLAKE  |     30 |
| CLARK  |     10 |
| SCOTT  |     20 |
| KING   |     10 |
| TURNER |     30 |
| ADAMS  |     20 |
| JAMES  |     30 |
| FORD   |     20 |
| MILLER |     10 |
+--------+--------+
mysql> select * from dept;
+--------+------------+----------+
| DEPTNO | DNAME      | LOC      |
+--------+------------+----------+
|     10 | ACCOUNTING | NEW YORK |
|     20 | RESEARCH   | DALLAS   |
|     30 | SALES      | CHICAGO  |
|     40 | OPERATIONS | BOSTON   |
+--------+------------+----------+

There are no conditional restrictions on the connection of two tables:

select ename,dname from emp, dept;
+--------+------------+
| ename  | dname      |
+--------+------------+
| SMITH  | ACCOUNTING |
| SMITH  | RESEARCH   |
| SMITH  | SALES      |
| SMITH  | OPERATIONS |
| ALLEN  | ACCOUNTING |
| ALLEN  | RESEARCH   |
| ALLEN  | SALES      |
| ALLEN  | OPERATIONS |
...
56 rows in set (0.00 sec)

14 * 4 = 56
When two tables are connected and queried without any condition restrictions, the number of final query results is the product of the number of two tables. This phenomenon is called: Cartesian product phenomenon. (Discovered by Descartes, this is a mathematical phenomenon.)

2.4. How to avoid the Cartesian product phenomenon?

Add conditions when connecting, and the records that meet this condition will be screened out!

select
ename,dname
from
emp, dept
where
emp.deptno = dept.deptno;
select
emp.ename,dept.dname
from
emp, dept
where
emp.deptno = dept.deptno;

// 表起别名。很重要。效率问题。

select
e.ename,d.dname
from
emp e, dept d
where
e.deptno = d.deptno; //SQL92 语法。

+--------+------------+
| ename  | dname      |
+--------+------------+
| CLARK  | ACCOUNTING |
| KING   | ACCOUNTING |
| MILLER | ACCOUNTING |
| SMITH  | RESEARCH   |
| JONES  | RESEARCH   |
| SCOTT  | RESEARCH   |
| ADAMS  | RESEARCH   |
| FORD   | RESEARCH   |
| ALLEN  | SALES      |
| WARD   | SALES      |
| MARTIN | SALES      |
| BLAKE  | SALES      |
| TURNER | SALES      |
| JAMES  | SALES      |
+--------+------------+

Thinking: The number of results in the final query is 14, but during the matching process, has the number of matches decreased?

Still 56 times, but one of four choices was made. The frequency did not decrease.

Note: According to the Cartesian product phenomenon, the more the number of table connections, the lower the efficiency. Try to avoid the number of table connections.

2.5. Equivalent connection of inner connection

Case: Query the department name of each employee, display the employee name and department name?

The emp e and dept d tables are joined. requirement is:e.deptno = d.deptno

SQL92 syntax:

select
e.ename,d.dname
from
emp e, dept d
where
e.deptno = d.deptno;

Disadvantages of sql92: the structure is not clear, the connection conditions of tables, and the conditions for further filtering in the later stage are all placed after where.

SQL99 syntax:

select
e.ename,d.dname
from
emp e
join
dept d
on
e.deptno = d.deptno;

//inner可以省略(带着inner可读性更好!!!一眼就能看出来是内连接)

select
e.ename,d.dname
from
emp e
inner join
dept d
on
e.deptno = d.deptno; // 条件是等量关系,所以被称为等值连接。

Advantages of sql99: The conditions for table connection are independent. After the connection, if further screening is required, continue to add where

SQL99 syntax:

select
...
from
a
join
b
on
a和b的连接条件
where
筛选条件

2.6. Non-equivalent connection of inner connection

Case: Find out the salary level of each employee, and ask to display the employee name, salary, and salary level?

mysql> select \* from emp; e
+-------+--------+-----------+------+------------+---------+---------+--------+
| 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 |
....

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

select
e.ename, e.sal, s.grade
from
emp e
join
salgrade s
on
e.sal between s.losal and s.hisal; // 条件不是一个等量关系,称为非等值连接。

select
e.ename, e.sal, s.grade
from
emp e
inner join
salgrade s
on
e.sal between s.losal and s.hisal;

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

2.7. Self-connection of inner connection

Case: Query the superior leader of the employee, and request to display the employee name and the corresponding leader name?

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

Tip: One table is regarded as two tables.

emp a employee table

+-------+--------+------+
| empno | ename  | mgr  |
+-------+--------+------+
|  7369 | SMITH  | 7902 |
|  7499 | ALLEN  | 7698 |
|  7521 | WARD   | 7698 |
|  7566 | JONES  | 7839 |
|  7654 | MARTIN | 7698 |
|  7698 | BLAKE  | 7839 |
|  7782 | CLARK  | 7839 |
|  7788 | SCOTT  | 7566 |
|  7839 | KING   | NULL |
|  7844 | TURNER | 7698 |
|  7876 | ADAMS  | 7788 |
|  7900 | JAMES  | 7698 |
|  7902 | FORD   | 7566 |
|  7934 | MILLER | 7782 |
+-------+--------+------+

emp b leader table

+-------+--------+------+
| empno | ename  | mgr  |
+-------+--------+------+
|  7369 | SMITH  | 7902 |
|  7499 | ALLEN  | 7698 |
|  7521 | WARD   | 7698 |
|  7566 | JONES  | 7839 |
|  7654 | MARTIN | 7698 |
|  7698 | BLAKE  | 7839 |
|  7782 | CLARK  | 7839 |
|  7788 | SCOTT  | 7566 |
|  7839 | KING   | NULL |
|  7844 | TURNER | 7698 |
|  7876 | ADAMS  | 7788 |
|  7900 | JAMES  | 7698 |
|  7902 | FORD   | 7566 |
|  7934 | MILLER | 7782 |
+-------+--------+------+

select
a.ename as '员工名', b.ename as '领导名'
from
emp a
join
emp b
on
a.mgr = b.empno; //员工的领导编号 = 领导的员工编号

+--------+--------+
| 员工名 | 领导名 |
+--------+--------+
| SMITH  | FORD   |
| ALLEN  | BLAKE  |
| WARD   | BLAKE  |
| JONES  | KING   |
| MARTIN | BLAKE  |
| BLAKE  | KING   |
| CLARK  | KING   |
| SCOTT  | JONES  |
| TURNER | BLAKE  |
| ADAMS  | SCOTT  |
| JAMES  | BLAKE  |
| FORD   | JONES  |
| MILLER | CLARK  |
+--------+--------+

13 records, no KING. "Inner Connection"

The above is the inner connection: self-connection, skill: one table is regarded as two tables.

2.8. Outer joins

mysql> select * from emp; e
+-------+--------+-----------+------+------------+---------+---------+--------+
| 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; d
+--------+------------+----------+
| DEPTNO | DNAME      | LOC      |
+--------+------------+----------+
|     10 | ACCOUNTING | NEW YORK |
|     20 | RESEARCH   | DALLAS   |
|     30 | SALES      | CHICAGO  |
|     40 | OPERATIONS | BOSTON   |
+--------+------------+----------+

Inner join: A and B are joined, and there is no primary and secondary relationship between the two tables of AB. equal.

select
e.ename,d.dname
from
emp e
join
dept d
on
e.deptno = d.deptno; //内连接的特点:完成能够匹配上这个条件的数据查询出来。

+--------+------------+
| ename  | dname      |
+--------+------------+
| CLARK  | ACCOUNTING |
| KING   | ACCOUNTING |
| MILLER | ACCOUNTING |
| SMITH  | RESEARCH   |
| JONES  | RESEARCH   |
| SCOTT  | RESEARCH   |
| ADAMS  | RESEARCH   |
| FORD   | RESEARCH   |
| ALLEN  | SALES      |
| WARD   | SALES      |
| MARTIN | SALES      |
| BLAKE  | SALES      |
| TURNER | SALES      |
| JAMES  | SALES      |
+--------+------------+

2.8.1. Outer join (right outer join)

select
e.ename,d.dname
from
emp e
right join
dept d
on
e.deptno = d.deptno;

// outer 是可以省略的,带着可读性强。
select
e.ename,d.dname
from
emp e
right outer join
dept d
on
e.deptno = d.deptno;

What does right stand for: It means that the table on the right of the join keyword is regarded as the main table, mainly to query all the data in this table, and the table on the left is incidentally associated with the query.

In the outer join, the two tables are joined, resulting in a primary and secondary relationship.

2.8.2. Outer join (left outer join)

select
e.ename,d.dname
from
dept d
left join
emp e
on
e.deptno = d.deptno;

// outer 是可以省略的,带着可读性强。
select
e.ename,d.dname
from
dept d
left outer join
emp e
on
e.deptno = d.deptno;

With right is the right outer connection, also known as the right connection. With left is a left outer connection, also known as a left connection.

Any right join has a left join. Any left join has a right join.

+--------+------------+
| ename  | dname      |
+--------+------------+
| CLARK  | ACCOUNTING |
| KING   | ACCOUNTING |
| MILLER | ACCOUNTING |
| SMITH  | RESEARCH   |
| JONES  | RESEARCH   |
| SCOTT  | RESEARCH   |
| ADAMS  | RESEARCH   |
| FORD   | RESEARCH   |
| ALLEN  | SALES      |
| WARD   | SALES      |
| MARTIN | SALES      |
| BLAKE  | SALES      |
| TURNER | SALES      |
| JAMES  | SALES      |
| NULL   | OPERATIONS |
+--------+------------+

Thinking: The number of query results for the outer join must be >= the number of query results for the inner join?

correct.

Case: Query the superior leader of each employee, and ask to display the names and leaders of all employees?

select
a.ename as '员工名', b.ename as '领导名'
from
emp a
left join
emp b
on
a.mgr = b.empno;
+--------+--------+
| 员工名 | 领导名 |
+--------+--------+
| SMITH  | FORD   |
| ALLEN  | BLAKE  |
| WARD   | BLAKE  |
| JONES  | KING   |
| MARTIN | BLAKE  |
| BLAKE  | KING   |
| CLARK  | KING   |
| SCOTT  | JONES  |
| KING   | NULL   |
| TURNER | BLAKE  |
| ADAMS  | SCOTT  |
| JAMES  | BLAKE  |
| FORD   | JONES  |
| MILLER | CLARK  |
+--------+--------+

2.9. How to connect three tables and four tables?

grammar:

select
...
from
a
join
b
on
a 和 b 的连接条件
join
c
on
a 和 c 的连接条件
right join
d
on
a 和 d 的连接条件

Inner joins and outer joins can be mixed in a SQL. can appear!

Case: Find out the department name and salary level of each employee, and ask to display the employee name, department name, salary, and salary level?

select
e.ename,e.sal,d.dname,s.grade
from
emp e
join
dept d
on
e.deptno = d.deptno
join
salgrade s
on
e.sal between s.losal and s.hisal;

+--------+---------+------------+-------+
| ename  | sal     | dname      | grade |
+--------+---------+------------+-------+
| SMITH  |  800.00 | RESEARCH   |     1 |
| ALLEN  | 1600.00 | SALES      |     3 |
| WARD   | 1250.00 | SALES      |     2 |
| JONES  | 2975.00 | RESEARCH   |     4 |
| MARTIN | 1250.00 | SALES      |     2 |
| BLAKE  | 2850.00 | SALES      |     4 |
| CLARK  | 2450.00 | ACCOUNTING |     4 |
| SCOTT  | 3000.00 | RESEARCH   |     4 |
| KING   | 5000.00 | ACCOUNTING |     5 |
| TURNER | 1500.00 | SALES      |     3 |
| ADAMS  | 1100.00 | RESEARCH   |     1 |
| JAMES  |  950.00 | SALES      |     1 |
| FORD   | 3000.00 | RESEARCH   |     4 |
| MILLER | 1300.00 | ACCOUNTING |     2 |
+--------+---------+------------+-------+

Case: find out the department name and salary level of each employee, as well as the superior leader, request to display the employee name, leader name, department name, salary, salary level?

select
e.ename,e.sal,d.dname,s.grade,l.ename
from
emp e
join
dept d
on
e.deptno = d.deptno
join
salgrade s
on
e.sal between s.losal and s.hisal
left join
emp l
on
e.mgr = l.empno;

+--------+---------+------------+-------+-------+
| ename  | sal     | dname      | grade | ename |
+--------+---------+------------+-------+-------+
| SMITH  |  800.00 | RESEARCH   |     1 | FORD  |
| ALLEN  | 1600.00 | SALES      |     3 | BLAKE |
| WARD   | 1250.00 | SALES      |     2 | BLAKE |
| JONES  | 2975.00 | RESEARCH   |     4 | KING  |
| MARTIN | 1250.00 | SALES      |     2 | BLAKE |
| BLAKE  | 2850.00 | SALES      |     4 | KING  |
| CLARK  | 2450.00 | ACCOUNTING |     4 | KING  |
| SCOTT  | 3000.00 | RESEARCH   |     4 | JONES |
| KING   | 5000.00 | ACCOUNTING |     5 | NULL  |
| TURNER | 1500.00 | SALES      |     3 | BLAKE |
| ADAMS  | 1100.00 | RESEARCH   |     1 | SCOTT |
| JAMES  |  950.00 | SALES      |     1 | BLAKE |
| FORD   | 3000.00 | RESEARCH   |     4 | JONES |
| MILLER | 1300.00 | ACCOUNTING |     2 | CLARK |
+--------+---------+------------+-------+-------+

3. Subqueries?

3.1. What is a subquery?

A select statement is nested in a select statement, and the nested select statement is called a subquery.

3.2. Where can subqueries appear?

select
..(select).
from
..(select).
where
..(select).

3.2. Subqueries in the where clause

Example: Find out the names and salaries of employees who are higher than the minimum wage?

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

ERROR 1111 (HY000): Invalid use of group function

Grouping functions cannot be used directly in the where clause.

Implementation ideas:

Step 1: Find out what the minimum wage is

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

Step 2: find out >800

select ename,sal from emp where sal > 800;

Step Three: Merge

select ename,sal from emp where sal > (select min(sal) from emp);
+--------+---------+
| ename  | sal     |
+--------+---------+
| 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 |
+--------+---------+

3.3. Subqueries in the from clause

Note: The subquery after from can treat the query result of the subquery as a temporary table. (Skill)

Example: Find the pay grade for the average salary for each position.

Step 1: Find the average salary for each position (average by position group)

select job,avg(sal) from emp group by job;
+-----------+-------------+
| job       | avgsal      |
+-----------+-------------+
| ANALYST   | 3000.000000 |
| CLERK     | 1037.500000 |
| MANAGER   | 2758.333333 |
| PRESIDENT | 5000.000000 |
| SALESMAN  | 1400.000000 |
+-----------+-------------+t表

Step 2: Overcome psychological barriers and treat the above query results as a real table t.

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

The t table and the s table are connected, the condition: t table avg(sal) between s.losal and s.hisal;

select
t.*, s.grade
from
(select job,avg(sal) as avgsal from emp group by job) t
join
salgrade s
on
t.avgsal between s.losal and s.hisal;

+-----------+-------------+-------+
| job       | avgsal      | grade |
+-----------+-------------+-------+
| CLERK     | 1037.500000 |     1 |
| SALESMAN  | 1400.000000 |     2 |
| ANALYST   | 3000.000000 |     4 |
| MANAGER   | 2758.333333 |     4 |
| PRESIDENT | 5000.000000 |     5 |
+-----------+-------------+-------+

3.4. The subquery that appears after select (this content does not need to be mastered, just understand it!!!)

Case: Find out the department name of each employee, and ask to display the employee name, department name?

select
e.ename,e.deptno,(select d.dname from dept d where e.deptno = d.deptno) as dname
from
emp e;

+--------+--------+------------+
| ename  | deptno | dname      |
+--------+--------+------------+
| SMITH  |     20 | RESEARCH   |
| ALLEN  |     30 | SALES      |
| WARD   |     30 | SALES      |
| JONES  |     20 | RESEARCH   |
| MARTIN |     30 | SALES      |
| BLAKE  |     30 | SALES      |
| CLARK  |     10 | ACCOUNTING |
| SCOTT  |     20 | RESEARCH   |
| KING   |     10 | ACCOUNTING |
| TURNER |     30 | SALES      |
| ADAMS  |     20 | RESEARCH   |
| JAMES  |     30 | SALES      |
| FORD   |     20 | RESEARCH   |
| MILLER |     10 | ACCOUNTING |
+--------+--------+------------+

//错误:ERROR 1242 (21000): Subquery returns more than 1 row
select
e.ename,e.deptno,(select dname from dept) as dname
from
emp e;

Note: For the subquery behind select, this subquery can only return one result at a time, if there are more than one result, an error will be reported!

4. union merge query result sets

Case: Query jobs are employees of MANAGER and SALESMAN?

select ename,job from emp where job = 'MANAGER' or job = 'SALESMAN';
select ename,job from emp where job in('MANAGER','SALESMAN');
+--------+----------+
| ename  | job      |
+--------+----------+
| ALLEN  | SALESMAN |
| WARD   | SALESMAN |
| JONES  | MANAGER  |
| MARTIN | SALESMAN |
| BLAKE  | MANAGER  |
| CLARK  | MANAGER  |
| TURNER | SALESMAN |
+--------+----------+

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

+--------+----------+
| ename  | job      |
+--------+----------+
| JONES  | MANAGER  |
| BLAKE  | MANAGER  |
| CLARK  | MANAGER  |
| ALLEN  | SALESMAN |
| WARD   | SALESMAN |
| MARTIN | SALESMAN |
| TURNER | SALESMAN |
+--------+----------+

union is more efficient. For table joins, every time a new table is connected, the number of matches satisfies the Cartesian product and doubles. But union can reduce the number of matches. In the case of reducing the number of matches, the splicing of two result sets can also be completed.

a connection b connection c, a 10 records, b 10 records, c 10 records, the number of matches is: 1000

a connect b a result: 10 * 10 --> 100 times

a connect c a result: 10 * 10 --> 100 times

Using union is: 100 times + 100 times = 200 times. (union turns multiplication into addition)

Are there any precautions when using union?

//错误的:union在进行结果集合并的时候,要求两个结果集的列数相同。
select ename,job from emp where job = 'MANAGER'
union
select ename from emp where job = 'SALESMAN';

// MYSQL可以,oracle语法严格 ,不可以,报错。要求:结果集合并时列和列的数据类型也要一致。
select ename,job from emp where job = 'MANAGER'
union
select ename,sal from emp where job = 'SALESMAN';
+--------+---------+
| ename  | job     |
+--------+---------+
| JONES  | MANAGER |
| BLAKE  | MANAGER |
| CLARK  | MANAGER |
| ALLEN  | 1600    |
| WARD   | 1250    |
| MARTIN | 1250    |
| TURNER | 1500    |
+--------+---------+

5. limit (very important)

5.1. limit

Function: Take out part of the query result set. Usually used in paging queries.

Baidu default: display 10 records on one page. The function of pagination is to improve the user experience, because all of them are checked out at once, and the user experience is poor. It can be viewed page by page.

5.2. How to use limit?

Complete usage: limit startIndex, length, startIndex is the start subscript, length is the length, and the start subscript starts from 0.

Default usage: limit 5; this is the first 5.

In descending order of salary, take out the top 5 employees?

select
ename,sal
from
emp
order by
sal desc
limit 5; //取前5

select
ename,sal
from
emp
order by
sal desc
limit 0,5;

+-------+---------+
| ename | sal     |
+-------+---------+
| KING  | 5000.00 |
| SCOTT | 3000.00 |
| FORD  | 3000.00 |
| JONES | 2975.00 |
| BLAKE | 2850.00 |
+-------+---------+

Note: limit in mysql is executed after order by! ! ! ! ! !

5.3. Take out the employees whose salary rank is [3-5]?

select
ename,sal
from
emp
order by
sal desc
limit
2, 3;
// 2 表示起始位置从下标 2 开始,就是第三条记录。
// 3 表示长度。

+-------+---------+
| ename | sal     |
+-------+---------+
| FORD  | 3000.00 |
| JONES | 2975.00 |
| BLAKE | 2850.00 |
+-------+---------+

5.4. Take out the employees whose salary rank is [5-9]?

select
ename,sal
from
emp
order by
sal desc
limit
4, 5;

+--------+---------+
| ename  | sal     |
+--------+---------+
| BLAKE  | 2850.00 |
| CLARK  | 2450.00 |
| ALLEN  | 1600.00 |
| TURNER | 1500.00 |
| MILLER | 1300.00 |
+--------+---------+

5.5. Paging

Display 3 records per page:

  • Page 1: limit 0,3[0 1 2],
  • Page 2: limit 3,3 [3 4 5],
  • Page 3: limit 6,3 [6 7 8],
  • Page 4: limit 9,3 [9 10 11]

Display pageSize records
per page pageNo page:limit (pageNo - 1) * pageSize , pageSize

public static void main(String[] args){
    
    
  // 用户提交过来一个页码,以及每页显示的记录条数
  int pageNo = 5; //第5页
  int pageSize = 10; //每页显示10条

  int startIndex = (pageNo - 1) * pageSize;
  String sql = "select ...limit " + startIndex + ", " + pageSize;
}

Remember the formula:limit (pageNo-1) * pageSize , pageSize

6. Summary of DQL statements

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

Execution order?

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

7. Table creation (build table)

7.1. The grammatical format of creating a table: (creating a table belongs to a DDL statement, and DDL includes: create drop alter)

create table table name (field name 1 data type, field name 2 data type, field name 3 data type);

create table 表名(
  字段名1 数据类型,
  字段名2 数据类型,
  字段名3 数据类型
);

Table name: It is recommended t*to tbl*start with or , which is more readable. See the name and know the meaning. Field name: see the name for meaning.

Both table names and field names are identifiers.

7.2. About data types in mysql?

Many data types, we only need to master some common data types.

7.2.1. varchar

The maximum length is 255, a variable-length string, which is smarter and saves space. The space will be allocated dynamically according to the actual data length.

Advantages: save space. Disadvantages: need to dynamically allocate space, slow speed.

7.2.2. char

The maximum length is 255, a fixed-length character string, regardless of the actual data length. Allocate fixed-length space to store data. When used improperly, it may lead to a waste of space.

Advantages: No dynamic allocation of space is required, and the speed is fast. Disadvantages: Improper use may lead to waste of space.

How should we choose between varchar and char?

What do you choose for the gender field? Choose char because gender is a fixed-length string.

What do you choose for the name field? The length of each person's name is different, so choose varchar.

7.2.3. int

Up to 11, the integer type in the number. Equivalent to java's int.

7.2.4. bigint

A long integer in a number. Equivalent to long in java.

7.2.5. float

Single-precision floating-point data

7.2.6. double

double-precision floating-point data

7.2.7. date

short date type

7.2.8. datetime

long date type

7.2.9. clob

Character large objects can store up to 4G strings. For example: store an article, store a description. All characters longer than 255 must be stored in CLOB character large objects.

Character Large OBject:CLOB

7.2.10. blob

Binary Large Object, Binary Large OBject, is specially used to store streaming media data such as pictures, sounds, and videos.

When inserting data into a field of BLOB type, such as inserting a picture, video, etc., you need to use IO streams.

t_movie movie table (dedicated to store movie information)

--------------------------------------------------------------------------------------------------------
   编号           名字          故事情节        上映日期           时长           海报          类型
--------------------------------------------------------------------------------------------------------
no(bigint)  name(varchar)   history(clob)   playtime(date)   time(double)    image(blob)    type(char)
--------------------------------------------------------------------------------------------------------
  10000           哪吒                         2019-10-11         2.5                          '1'
  10001        林正英之娘娘                     2019-11-11         1.5                          '2'
--------------------------------------------------------------------------------------------------------

7.3. Create a student table?

Student number, name, age, gender, email address

create table t_student(
no int,
name varchar(32),
sex char(1),
age int(3),
email varchar(255)
);

drop table:

drop table t_student; // 当这张表不存在的时候会报错!

// 如果这张表存在的话,删除
drop table if exists t_student;

7.4. Insert data insert (DML)

Grammar format:

insert into 表名(字段名 1,字段名 2,字段名 3...) values(1,2,3);

Note: Field names and values ​​must correspond one-to-one. What is one-to-one correspondence?

The quantity should correspond. The data type should correspond.

insert into t_student(no,name,sex,age,email) values(1,'zhangsan','m',20,'[email protected]');

insert into t_student(email,name,sex,age,no) values('[email protected]','lisi','f',20,2);

insert into t_student(no) values(3);

+------+----------+------+------+------------------+
| no   | name     | sex  | age  | email            |
+------+----------+------+------+------------------+
|    1 | zhangsan | m    |   20 | zhangsan@123.com |
|    2 | lisi     | f    |   20 | lisi@123.com     |
|    3 | NULL     | NULL | NULL | NULL             |
+------+----------+------+------+------------------+
insert into t_student(name) values('wangwu');
+------+----------+------+------+------------------+
| no   | name     | sex  | age  | email            |
+------+----------+------+------+------------------+
|    1 | zhangsan | m    |   20 | zhangsan@123.com |
|    2 | lisi     | f    |   20 | lisi@123.com     |
|    3 | NULL     | NULL | NULL | NULL             |
| NULL | wangwu   | NULL | NULL | NULL             |
+------+----------+------+------+------------------+

Note: As long as the insert statement is executed successfully, there must be one more record. If no value is specified for other fields, the default value is NULL.

drop table if exists t_student;
create table t_student(
no int,
name varchar(32),
sex char(1) default 'm',
age int(3),
email varchar(255)
);

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| no    | int(11)      | YES  |     | NULL    |       |
| name  | varchar(32)  | YES  |     | NULL    |       |
| sex   | char(1)      | YES  |     | m       |       |
| age   | int(3)       | YES  |     | NULL    |       |
| email | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
insert into t_student(no) values(1);
mysql> select * from t_student;
+------+------+------+------+-------+
| no   | name | sex  | age  | email |
+------+------+------+------+-------+
|    1 | NULL | m    | NULL | NULL  |
+------+------+------+------+-------+

Can the "field name" in the insert statement be omitted? Can

insert into t_student values(2); //错误的

// 注意:前面的字段名省略的话,等于都写上了!所以值也要都写上!
insert into t_student values(2, 'lisi', 'f', 20, '[email protected]');
+------+------+------+------+--------------+
| no   | name | sex  | age  | email        |
+------+------+------+------+--------------+
|    1 | NULL | m    | NULL | NULL         |
|    2 | lisi | f    |   20 | lisi@123.com |
+------+------+------+------+--------------+

7.5. insert insert date

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 |
+--------+---------+

Format numbers: format(number, 'format')

select ename,format(sal, '$999,999') as sal from emp;
+--------+-------+
| ename  | sal   |
+--------+-------+
| SMITH  | 800   |
| ALLEN  | 1,600 |
| WARD   | 1,250 |
| JONES  | 2,975 |
| MARTIN | 1,250 |
| BLAKE  | 2,850 |
| CLARK  | 2,450 |
| SCOTT  | 3,000 |
| KING   | 5,000 |
| TURNER | 1,500 |
| ADAMS  | 1,100 |
| JAMES  | 950   |
| FORD   | 3,000 |
| MILLER | 1,300 |
+--------+-------+
  • str_to_date: Convert string varchar type to date type
  • date_format: convert the date type into a varchar string type with a certain format.
drop table if exists t_user;
create table t_user(
id int,
name varchar(32),
birth date // 生日也可以使用date日期类型
);

create table t_user(
id int,
name varchar(32),
birth char(10) // 生日可以使用字符串,没问题。
);

Birthday: 1990-10-11 (10 characters)

Note: There is a naming convention in the database: all identifiers are all lowercase, and words are connected with underscores.

mysql> desc t_user;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(32) | YES  |     | NULL    |       |
| birth | date        | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

Insert data?

insert into t_user(id,name,birth) values(1, 'zhangsan', '01-10-1990'); // 1990 年 10 月 1 日

Something went wrong: the cause was a type mismatch. The database birth is of date type, here a string varchar is given.

what to do? You can use the str_to_date function for type conversion.

The str_to_date function can convert a string into a date type date?

Grammar format:

str_to_date('字符串日期', '日期格式')

mysql date format:

  • %Y years
  • %m months
  • %d days
  • at %h
  • %i minutes
  • %s seconds
insert into t_user(id,name,birth) values(1, 'zhangsan', str_to_date('01-10-1990','%d-%m-%Y'));

The str_to_date function can convert the string varchar into date type data, which is usually used in inserting, because a date type data is needed when inserting, and the string needs to be converted into date through this function.

good news?

If the date string you provide is in this format, the str_to_date function is not needed! ! !

%Y-%m-%d
insert into t_user(id,name,birth) values(2, 'lisi', '1990-10-01');

Can it be displayed in a specific date format when querying?
date_format
This function can convert the date type into a string of a specific format.

select id,name,date_format(birth, '%m/%d/%Y') as birth from t_user;
+------+----------+------------+
| id   | name     | birth      |
+------+----------+------------+
|    1 | zhangsan | 10/01/1990 |
|    2 | lisi     | 10/01/1990 |
+------+----------+------------+

How to use date_format function?

date_format(日期类型数据, '日期格式')

This function is usually used in querying dates. Set the date format to display.

mysql> select id,name,birth from t_user;
+------+----------+------------+
| id   | name     | birth      |
+------+----------+------------+
|    1 | zhangsan | 1990-10-01 |
|    2 | lisi     | 1990-10-01 |
+------+----------+------------+

The above SQL statement actually performs the default date formatting, and automatically converts the date type in the database to the varchar type. And the format used is mysql default date format: '%Y-%m-%d'

select id,name,date_format(birth,'%Y/%m/%d') as birth from t_user;

date format in java?yyyy-MM-dd HH:mm:ss SSS

7.6. What is the difference between date and datetime?

date is a short date: only year month day information is included.
datetime is a long date: including year, month, day, hour, minute, and second information.

drop table if exists t_user;
create table t_user(
    id int,
    name varchar(32),
    birth date,
    create_time datetime
);

id is an integer, name is a string, birth is a short date.

create_time is the creation time of this record: long date type

Mysql short date default format: %Y-%m-%d, long date default format: %Y-%m-%d %h:%i:%s

insert into t_user(id,name,birth,create_time) values(1,'zhangsan','1990-10-01','2020-03-18 15:49:50');

How to get the current time of the system in mysql?

now() function, and the obtained time has: hour, minute and second information! ! ! ! It is of datetime type.

insert into t_user(id,name,birth,create_time) values(2,'lisi','1991-10-01',now());

7.7. Modify update (DML)

Grammar format:

update 表名 set 字段名 1=1,字段名 2=2,字段名 3=3... where 条件;

Note: There are no conditional restrictions that will cause all data to be updated.

update t_user set name = 'jack', birth = '2000-10-11' where id = 2;
+------+----------+------------+---------------------+
| id   | name     | birth      | create_time         |
+------+----------+------------+---------------------+
|    1 | zhangsan | 1990-10-01 | 2020-03-18 15:49:50 |
|    2 | jack     | 2000-10-11 | 2020-03-18 15:51:23 |
+------+----------+------------+---------------------+

update t_user set name = 'jack', birth = '2000-10-11', create_time = now() where id = 2;

update all?

update t_user set name = 'abc';

7.8. Delete data delete (DML)

grammar format?

delete from 表名 where 条件;

Note: If there is no condition, all the data in the entire table will be deleted!

delete from t_user where id = 2;

insert into t_user(id) values(2);

delete from t_user; // 删除所有!

8. Download

8.1. This document

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

8.2. Involved data

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

9. Continue reading

9.1. Previous article

https://hty.ink/2260/

9.2. Next

https://hty.ink/2295/

Guess you like

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