1. Single table query
Data query language, specifically used to find data in tables.
select * from emp;
Keywords
select * from table name |
Query all data in table |
Source file address \ file name of the imported file |
Import dump data (cannot add ";" at the end ) |
The data backup file of mysql is called a dump file
-
Arithmetic
Four arithmetic operations +, -, *, / //The query can also be queried and output together with the operator
2. Remove duplicates
Keywords:
distinct。
Only when the data in all columns are the same, it will be deduplicated.
Syntax: select distinct column name from table name;
#Check which jobs are currently available.
select distinct job from emp;
3. where: filter
grammar:
select // query
column_name1, column_name2...
from // What table to locate
Table Name
where // Filter constraints
Filter conditions.
Filter criteria: Comparison operators:
>、<、<=、>=、!=、<>
- Execution process: first execute from to locate the table position, then execute where to perform conditional filtering, and finally execute select query output
Filtered result set.
- Virtual table: A virtual table generated when the result set is run in memory.
Virtual labels are used to store result sets
The result set is the part of the table displayed in the virtual mark
4. is null: empty
grammar:
select //query
column_name1, column_name2...
from //What table to locate
Table Name
where //Filter constraints
Column name is null //Indicates that the column name is empty
Example: Query information about employees without bonuses.
select * from emp where comm is null;
5. is not null: not empty
not can also be used in conjunction with other keywords to mean "not for"
grammar:
select //query
column_name1, column_name2...
from //What table to locate
Table Name
where //Filter constraints
Column name is not null //Indicates that the column name is not empty .
Example: Query information about employees with bonuses.
select * from emp where comm is not null;
6. and: and
grammar:
select //query
ename as name, // as represents an alias, ename will display the name as an alias when outputting the result set , only in the result set
sal as salary, // display, will not actually change the header of the table
from //What table to locate
Table Name
where //Filter constraints
Column name condition and column name condition //Indicates that the previous condition is met and the next condition is met.
Example: Query the name, salary, and bonus of employees whose salary is greater than 1,000 and who can receive bonuses.
select
ename as 姓名, sal 工资, comm 奖金
from emp
where
sal > 1000 and comm is not null;
7. or or
grammar:
select //query
column_name1, column_name2...
from //What table to locate
Table Name
where //Filter constraints
Column name condition 1 or column name condition 2 //Indicates that the query output meets condition 1 or meets condition 2
Example: Query the number, job, entry time, and salary of employees who are engaged in sales or whose salary is greater than or equal to 2000.
select
empno,job,hiredate,sal
from emp
where
job = 'salesman' or sal>=2000;
8. not: non, go against
grammar:
select
Column name 1, column name 2….
from
Table Name
where
not listing condition;
Example: Query the number, name, position, salary, and entry time of employees who are engaged in non-sales work and whose salary is not less than 1500.
select
ename,job,sal,hiredate
from emp
where
not (job="salesman") and not (sal<1500);
9. between and: interval
grammar
select
Column name 1, column name 2...
from
Table Name
where
Column name between condition and condition.
Note: between and is equivalent to: >= and <=, // characters can also be judged, and the value of the first letter will be judged.
Example: Query the information of employees whose salary is greater than 1500 but less than 3000
select
*
from
emp
where
sal between 1500 and 3000;
10. in: include, include meaning
grammar:
select
Column name 1, column name 2...
from
Table Name
where
Column name in (condition 1, condition 2...).
Example: Query the information of employees with numbers 7566, 7900, 7369, and 8888.
select
*
from
emp
where
empno in(7566,7900,7369,8888);
11. not in: not included
grammar:
select
Column name 1, column name 2...
from
Table Name
where
The column name is not in (condition 1, condition 2...).
Example: Query employee information that is not SMITH, MARTIN, Adams.
select
*
from
emp
where
ename not in('smith','martin','adams');
12. like: fuzzy matching
Need to be used in combination with 2 wildcards
- _match any character
- % matches any length of characters
grammar:
select
Column name 1, column name 2...
from
Table Name
where
Column name like condition
Example: The third character of the query name is the information of the employee of A.
select
*
from
emp
where
ename like '__a%';
//__ There are two '_ _' to indicate any character in the first two characters, if the third character is A , the characters in the following % are random
Example: Query the information of employees who joined in 1989.
select
*
from
emp
where
hiredate like '1988%';
13. order by: sorting
Grammar: if there is where, order by must follow where,
select
column_name1, column_name2...
from table name
where
filter conditions
order by
Sort column 1, sort column 2.... asc | desc; // '|' means or
The sorting rule will be sorted according to the sequence of sorting column 2 when the sorting column 1 is the same, and so on.
asc: Default, sort in ascending order, optional
desc: Sort in descending order
Example 1: Query employee information and sort by salary from low to high.
select
*
from emp
order by sal desc;
Example 2: Query the information of employees in department No. 10, and sort by salary from high to low.
select
*
from emp
where deptno=10
order by sal;
Example 3: Query the annual salary of all employees [(sal+comm)*12], sort by annual salary from high to low
select
ename,
(sal+ifnull(comm,0)) * 12 annual salary
from emp
order by annual salary desc;
sql execution process:
from -->where-->select -->order by
14. limit(startIndex,size): paging
grammar:
select
column_name1, column_name2...
from
Table Name
where
filter conditions
order by
Sort Column 1, Sort Column 2….asc
limit startIndex ,size;
startIndex: start index
size: take a few
Example:
#Get the employee information of the first 3 pieces of data constructed less than 1500
select
*
from
emo
where
sal<1500; // Get the table with salary less than 1500
limit (1-1)*3,3;
Paging algorithm:
Requirement: Each page displays 3 pieces of data. How many pages are displayed in total?
Query the first page of data
…
Query the data of the last page
Current page: Default 1
Total number of pages: total data volume/number of items displayed per page. 14/3=5
//When the computer calls paging, the bottom layer will eventually be called according to the paging algorithm.
Calculate the starting subscript: (current page -1 ) * The number of items displayed on each page;
Virtual table:
The virtual standard is many tables generated during the running of SQL, and the result set is one of the displayed tables in the virtual standard.
2. Multi-table query
1. Equivalent connection
Syntax: select
List name…
from
Table name 1 alias 1, table name 2 alias 2...
where
connection succeeded
select
e.*,d.*
from
emp e,dept d;
#The above query will appear Cartesian product query (cross query)
# Cartesian Product: A collection of two datasets.
// Because there is no connection condition
#Go to Dekal Product Query
Equijoin:
select e.*,b.*
from emp e,dept d
where
e.deptno=d.deptno; //需要通过两个表中相同的字段进行等值连接
Example 1: Query all data of emp table and dept table.
select
e.*,d.*
from
emp e,dept d
where
e.deptno = d.deptno;
Example 2: Query the number, name, salary and department name and department address of all employees.
select
e.empno,e.ename,e.sal,d.dname,d.loc
from
emp e,dept d
where
e.deptno=d.deptno;
Example 3: Query the number, name, salary, department name and department address of the employee whose department is 10.
select
e.empno,e.ename,e.sal,d.dname,d.loc
from
emp e,dept d
where
e.deptno=d.deptno
and
e.deptno=10;
Self-join: join of different fields in one table
Example 1: Query employee name, salary, leader name, leader salary.
select
e.ename,e.sal,e2.ename,e2.sal
from
emp e,emp e2 #一个表中建立两个对象
where
e.mgr=e2.empno; #emp表中e对象的mgr字段和e2对象的empno字段进行连接
Non-equijoin: and
Represents equivalent fields and non-equivalent fields for comparison and connection output.
Example: Query the employee's name, salary, department name, and employee's salary grade.
select
e.ename,e.sal,d.dname,s.grade 工资等级
from
emp e,dept d,salgrade s
where
e.deptno=d.deptno
and
e.sal between s.losal and s.hisal; //等值字段和范围字段进行输出
Example 2: Query the employee's name, salary, department name, employee's salary level, leader's salary, name, and salary level.
select
e.ename,e.sal,d.dname,s.grade employee salary grade,
m.ename leader name, m.sal leader salary, sm.grade leader salary grade
from
emp e,dept d,salgrade s,emp m,salgrade sm
where
e.deptno=d.deptno
and
e.mgr=m.ename
and
m.sal between sm.losal and sm.hisal;
SQL99:
SQL99 is a standard for data query statements, formulated in 1999
- Concept: One syntax for multi-table queries
- Classification
- inner join
- outer join
1. Inner join: It is equal value join (------ Only data with equal values can be put into the result set )
inner join on #inner keyword can be omitted
Equijoin
grammar:
select column name
from table name 1 alias 1 join table name 2 alias 2
on #Judge connection conditions
Connection conditions
join #When you need to re-add the table connection, it will be used as a connection
Table name 3 Alias 3
on #Conditions for reconnection
connection conditions;
Example: Query the name, salary, department name, and leader name of employees whose salary is greater than 1500
select
e.ename,e.sal,d.dname,m.ename
from emp e
join dept d on e.deptno = d.deptno #两个表进行连接
join emp m on e.mgr = m.empno #新加入一个
where
e.sal > 1500;
2. Outer connection
left: left outer join ------ take the table on the left as the main table (all the data in the main table will display the result set, and the data that does not exist in the secondary table will display null)
Always display all the data in the table on the left in from. If the data on the right matches the data, the matching data will be displayed. If there is no match, null will be displayed;
grammar:
select a.name,b.job
from t_b b left
join t_a a
on b.a_id = a.id;
right: right outer join-----use the right side as the main table (same as above, that is, use the right side of the join as the main table)
Always show data on the right
grammar:
select a.name, b.job
from t_b b
right join t_a a
on b.a_id = a.id;
Example: Query employee names and department names, department addresses, including departments without personnel.
select e.ename, d.dname, d.loc
from emp e
right join dept d
on e.deptno = d.deptno;
3. Group statistics combined with aggregation functions:
Keyword: group by
grammar:
select column name 1
from table name
where
filter conditions
group by
Group 1, Group 2....
order by
Sorting column 1.... limit
Sample data
create table t_group(
id int,
name varchar(20),
num int
);
create table t_group(
id int,
name varchar(20),
num int
);
insert into t_group values(1,'aa',2);
insert into t_group values(2,'aa',3);
insert into t_group values(3,'bb',4);
insert into t_group values(4,'bb',5);
insert into t_group values(5,'cc',6);
insert into t_group values(6,'dd',7);
insert into t_group values(7,'bb',5);
insert into t_group values(8,'ee',8);
insert into t_group values(9,'cc',6);
Example: Group the data in the t_group table by name.
select *
from t_group
group by name;
having: used to filter grouped data
Keywords
The where statement filters data before grouping. The where statement is run before group by and having.
The grouped data needs to be filtered using the having keyword
Execution order: from -->on(where---join) -->group by -->select--> having -->order by-->limit ( paging )
Example: Query the department number and average salary where the average salary is greater than 2,000 yuan.
select d.dname,avg(e.sal)
from emp e, dept d
where e.deptno=d.deptno
group by d.deptno
having avg(e.sal)>2000;
Example : Query the name of a department with more than 3 employees and the number of employees.
select d.dname,count(e.ename)
from emp e
join dept d
on e.deptno=d.deptno
group by d.deptno
having count(e.ename)>3;
Subquery:
1. Concept: The result of a query is used as the condition of another query, which is called a subquery. Also called nested query
During operation, the judgment condition is first obtained, and then the judgment condition is embedded in the main code output.
2. The judgment condition is segmented understanding. If the filter condition does not require grouping, use where , and if the filter condition does not require grouping, use having ;
The data that needs to be viewed is obtained by using select , the table that needs to be used in the middle is written in from , and the average salary that needs to be requested later is the filter condition
The running process is as shown in the figure:
1. First find out the average salary of the company
2. Write the table you need to use through from
3. Write the filtering conditions under where as a requirement
4 Write out the columns that need to be viewed through select
Example 1: Query what is the salary of the person with the highest salary in the company, what is the name?
---What is the highest salary in the company?
select max(sal) from emp;
select sal, ename
from emp
where
sal=(select max(sal) from emp); #Query the maximum salary
Example 2: Query information about employees whose salary is higher than 7698.
select sal from emp where empno=7698 //Get the salary of the person with the highest salary first
select
* from emp
where
sal> (select sal from emp where empno=7698); #Take the salary of the person with the highest salary as the condition
subquery:
- single column subquery
- The returned result set is a single row and single column
Use the combining operators > < = !=
multi-row subquery
The result set returned is multiple rows and single column. Combined operator in any all
multi-column subquery
- The result set returned is multiple rows and columns (can be regarded as a result set)
1. Single column subquery
Example 1: Query the number and minimum salary of each department, requiring the minimum salary to be greater than or equal to the minimum salary of department 30
--What is the minimum wage for department 30? (Find the minimum wage first)
select min(sal) from emp where deptno =30;
select deptno min(sal) minimum wage #minimum wage is an alias of min(sal),
from emp
group by deptno
having minimum wage> select min(sal) from emp where deptno =30;
Example 2: Query the name of the department, the number of employees in the department, the average salary of the department, and the name of the lowest-paid employee in the department.
select ename from emp where sal =min(sal)
select d.dname department number, count(e.ename) number of department employees, avg(e.sal) department average salary,
(select ename from emp where sal =min(e.sal)) Department minimum wage name
from dept d
left join emp e
on d.deptno=e.deptno
group by d.deptno;
2. Multi-row subquery
Usually used to make a judgment condition
- Mainly use operators
- in: contains
- any : greater than any, less than any
- =any: equivalent to in, generally used relatively rarely
- >any: greater than the minimum value inside
<any : less than the maximum value inside
all : greater than the largest, less than the smallest
>all: greater than the maximum value inside
<all: less than the minimum value inside
-
in Example: Query employee information whose salary is the same as that of all employees in department 20
---What is the salary of employees in department 20?
select sal from emp where deptno=20;
select *
from emp
where sal in(select sal from emp where deptno=20);
1. all keyword
Example: Query employee information whose salary is greater than that of each department manager
--- First find out the salary of each department manager
select sal from emp where job='manager';
select *
from emp e
join (select sal,deptno from emp where job='manager') m
on e.deptno=m.deptno
group by e.deptno
having e.deptno=m.deptno
and e.sal>m.sal;
2. Multi-column subquery
A multi-column subquery returns multiple rows and multiple columns, or a single row and multiple columns
Commonly used on the result set, used as a table ( used in from )
Example: Information about employees whose salary is greater than 1500 appears in the sales job
----Who is engaged in sales?
select * from emp where job = 'salesman'
multi-table exercises
1. List the names of departments with at least 4 employees
select d.dname
from emp e join dept d
on e.deptno=d.deptno
group by d.deptno
having
count(e.ename)>4;
2. List all employees whose salary is more than "SMITH"
select ename
from emp
where
sal>(select sal from emp where ename='SMITH');
3. List the names of all employees and the names of their immediate supervisors
select e.ename,m.ename
from emp e, emp m
where
e.mgr=m.empno;
4. List the numbers, names, and department names of all employees whose employment dates are earlier than their immediate superiors
select e.empno,e.ename,d.dname
from emp e, emp m, dept d
where
e.mgr=m.empno
and
e.deptno=d.deptno
and
e.hiredate<m.hiredate;
5. List the names of all employees engaged in "CLERK" work, their department names, and department headcount
select count(ename) Number of people in the department, deptno from emp group by deptno; #First get the number of people in each department
select
e.ename,d.dname,t.Department headcount
from emp e join dept d
on e.deptno=d.deptno
join
(select count(ename) department headcount,deptno from emp group by deptno) t #Because the department headcount is a table
on e.deptno=t.deptno
where job='clerk';
6. List the names of employees working in the department "SALES" (Sales Department). It is assumed that the department number of the Sales Department is not known.
select
ename
from
emp
where
deptno=(select deptno from dept where dname ='sales');