MySQL study notes (2)-DML statement

Introduction

DML (Data Manipulation Language) data manipulation language : used to add, delete, change, query, and check data integrity of database records. Commonly used keywords are insert (insert), delete (delete), update (update), select (query) and so on.

Specific steps

Insert record

INSERT INTO tablename (field1, field2,…, fieldn) VALUES( value1, value2,…, valuen);

Fields in the table:
Insert picture description here
For example, insert the following records into the table emp: ename is llw1, hiredate is 2020-01-01, sal is 20000, the command execution is as follows:

mysql>insert into emp (ename, hiredate, sal, deptno) values('llw1', '2020-01-01', '20000', 1);

It is not necessary to specify the field name, but the order of values ​​should be consistent with the order of the fields, for example:

mysql>insert into emp values('lw', '2018-01-01', '30000', 2);

You can also explicitly insert only the "ename" and "sal" fields in the table:

mysql>insert into emp (ename, sal) values('llw2', '20000');

The results show that
Insert picture description here
these unwritten fields can be automatically set to NULL, the default value, and the next number incremented, which can greatly reduce the complexity of the SQL statement in some cases.

Insert multiple items at once:

INSERT INTO tablename (field1, field2, …, fieldn)
VALUES
(record1_value1, record1_value2, …, record1_valuesn),
(record2_value1, record2_value2, …, record2_valuesn),

(recordn_value1, recordn_value2, …, recordn_valuesn);

E.g:

mysql>insert into dept values(5,'dept5'),(6,'dept6');

The results show that:
Insert picture description here

update record

The record value in the table can be changed by the update command, the syntax is as follows:

UPDATE tablename SET field1=value1,field2.=value2,…,fieldn=valuen [WHERE CONDITION]

For example, change the salary (sal) with ename "llw1" in the table emp from 20000 to 10000:

mysql> update emp set sal = 10000 where ename='llw1';

The results show: The
Insert picture description here
update command can also update data in multiple tables at the same time, the syntax is as follows:

UPDATE t1,t2,…,tn set t1.field1=expr1,tn.fieldn=exprn [WHERE CONDITION]

E.g:

mysql>update emp a,dept b set a.sal=a.sal*2, b.deptname=a.ename where a.deptno=2;

The results show that:
Insert picture description here

Delete Record

If the record is no longer needed, you can use the delete command to delete, the syntax is as follows:

DELETE FROM tablename [WHERE CONDITION]

E.g:

mysql>delete from emp where ename='llw2';

In MySQL, you can delete data from multiple tables at once. The syntax is as follows:

DELETE t1,t2,…,tn FROM t1,t2,…,tn [WHERE CONDITION]

mysql>delete a,b from emp a,dept b where a.deptno=2 and b.deptno=6;

The results show that:
Insert picture description here

Query the records

The syntax of SELECT is very complicated, only the most basic syntax is introduced here:

SELECT * FROM tablename [WHERE CONDITION]

mysql>select * from emp;

Insert picture description here
Which “*”means that all records should be displayed, or all fields separated by commas can be used instead, for example:

mysql>select ename,hiredate,sal,deptno from emp;

Query unique records

The distinct keyword can be used to display records without repeating them, for example:

mysql>select distinct ename from emp;

The results show that:
Insert picture description here

Conditional query

Display records with " deptno " as " 1 ":

mysql>select * from emp where deptno = 1;

The results show:
Insert picture description here
the above example, WHERE latter condition is a = field comparison, in addition to = , but also may be used > , < , > = , <= , ! = , Etc. comparison operators; among a plurality of conditions may also be Use logical operators such as or , and to perform multi-condition joint query

The results show that:
Insert picture description here

Sort and limit

If you want to display the results sorted by a field, you can use the keyword order by to achieve, the syntax is as follows:

SELECT * FROM tablename [WHERE CONDITION] [ORDER BY field1 [DESC|ASC],field2 [DESC|ASC],…,fieldn [DESC|ASC]]

Among them, DESC and ASC are sort order keywords, DESC means descending order according to the field, ASC means ascending order, if you do not write this keyword, the default is ascending order. ORDER BY can be followed by multiple different sort fields, and each sort field can have a different sort order.

E.g:

mysql>select * from emp order by sal desc;

The records are displayed in descending order of sal . The results are as follows:
Insert picture description here
If the values ​​of the sort fields are the same, the fields with the same value are sorted according to the second sort field, and so on. If there is only one sort field, the records with the same field will be randomly arranged.

After the records are sorted, if you only want to display a part of the records, you can use the limit keyword to achieve, the syntax is as follows:

SELECT …[LIMIT offset_start,row_count]

E.g:

mysql>select * from emp order by sal desc limit 3;

Only the first 3 records are
Insert picture description here
displayed. The result is as follows: the mth to nth records are displayed.

For example, showing records 2 to 3:

mysql>select * from emp order by sal desc limit 1, 2;

The results are as follows:
Insert picture description here

polymerization

In many cases, users need to perform some summary operations, such as counting the number of people in the entire company or counting the number of people in each department. At this time, SQL aggregation operations are used.

The syntax of the aggregation operation is as follows:

SELECT [field1,field2,…,fieldn]
fun_name FROM tablename
[WHERE here_contition]
[GROUP BY field1,field2,…,fieldn [WITH ROLLUP]]
[HAVING where_contition]

The following description of its parameters:

fun_name represents the aggregation operation to be done, that is, the aggregation function. Commonly used are sum (sum), count (*) (number of records), max (maximum value), min (minimum value).
The GROUP BY keyword indicates the field to be classified and aggregated. For example, to count the number of employees according to the department classification, the department should be written after group by.
WITH ROLLUP is an optional syntax that indicates whether to re-aggregate the results after classification aggregation.
The HAVING keyword means to conditionally filter the classified results.

note:

The difference between having and where is that having is a conditional filtering of the aggregated results, while where is to filter the records before the aggregation. If the logic allows, we use the where to filter the records as much as possible, because the result set is reduced , Will greatly improve the efficiency of aggregation, and finally according to the logic to see whether to use filtering to re-filter.

The records in the current table are as follows:
Insert picture description here
For example, the total number of companies in the emp table is counted:

mysql>select count(1) from emp;

Insert picture description here
Count the number of people in each department:

mysql>select deptno,count(1) from emp group by deptno;

Insert picture description here
It is necessary to count the number of people in each department and the total number of people:

mysql> select deptno, count(1) from emp group by deptno with rollup;

Insert picture description here
Departments with more than 1 statistic:

mysql> select deptno,count(1) from emp group by deptno having count(1) > 1;

Insert picture description here
Calculate the total salary, maximum and minimum salary of all employees of the company:

mysql> select sum(sal), max(sal), min(sal) from emp;

Insert picture description here

Table connection

When you need to display fields in multiple tables at the same time, you can use a table connection to achieve such a function. In terms of categories, table joins are divided into inner joins and outer joins. The main difference between them is that inner joins only select records that match each other in the two tables, while outer joins select other unmatched records.

The records in the current table are as follows:
Insert picture description here
Insert picture description here
our most commonly used is the internal connection. For example, query out the names of all employees and the name of the department:

mysql> select ename, deptname from emp, dept where emp.deptno = dept.deptno;

Insert picture description here
External connections are divided into left and right connections, which are defined as follows.

Left join: contains all the records in the left table and even the records in the right table that do not match it.
Right join: contains all the records in the right table and even the records in the left table that do not match it.

For example, to query all department names and corresponding employee names in dept:

mysql> select ename, deptname from emp right join dept on emp.deptno = dept.deptno;

No employee in the emp record corresponds to the " lw " department, and the results are displayed as follows:
Insert picture description here

Subquery

In some cases, when performing a query, the required condition is the result of another select statement. At this time, a subquery is used. The keywords used for subqueries mainly include in, not in, =,! =, Exists, not exists, etc.

All records in the current emp table: Records in the
Insert picture description here
dept table:
Insert picture description here
For example, from the emp table, all records in all departments in the dept table are queried:

mysql> select * from emp where deptno in(select deptno from dept);

Insert picture description here
Since the department where "llw5" is located has no record in the dept table, it is not displayed.

Subqueries can be converted into table joins. For example, the above statement can be expressed as a table join:

mysql> select emp.* from emp ,dept where emp.deptno=dept.deptno;

Insert picture description here

Note: The conversion between subqueries and table joins is mainly used in two ways.
MySQL versions prior to 4.1 do not support subqueries. You need to use table joins to implement subqueries.
Table joins are used to optimize subqueries in many cases.

Record union

After querying the data of the two tables according to certain query conditions, the results are combined and displayed together. At this time, you need to use the union and union all keywords to achieve such a function. The specific syntax is as follows:
SELECT * FROM t1
UNION | UNION ALL
SELECT * FROM t2

UNION | UNION ALL
SELECT * FROM tn;
The main difference between UNION and UNION ALL is that UNION ALL directly merges the result sets together, and UNION performs the DISTINCT of the results after UNION ALL to remove The result after repeated recording.

Take the following example to display the set of department numbers in the emp and dept tables:

mysql> select deptno from emp union all select deptno from dept;

The results are as follows:
Insert picture description here
remove duplicate records:

mysql> select deptno from emp union select deptno from dept;

The results are as follows:
Insert picture description here

Published 2 original articles · Likes2 · Visits 36

Guess you like

Origin blog.csdn.net/weixin_43587255/article/details/105464583