Summary of basic knowledge points of mysql (2)

2. Multi-table query

1. Remove duplicate records (deduplicate the query results without changing the records in the original table) distinct

select ename, distinct job from emp; //This is wrong to write, distinct can only appear at the front of all fields.

select distinct job, deptno from emp; //distinct appears before the two fields job and deptno, indicating that the two fields are combined to remove duplication.

Count the number of jobs select count (distinct job) from emp;

2. Connection query (very important)

2.1 What is a join query? The combination of multiple tables to query data is called a join query.

2.2 Classification of connection queries?

Chronological classification based on grammar? 1992 sql92; 1999 sql99;

Inner joins (equivalent joins, non-equivalent joins, self-joins) and outer joins (left outer join, right outer join)

2.3 When two tables are connected, there is no restriction, and a connection is performed according to the Cartesian product method. The number of entries in the final query result is the product of the number of entries in the two tables;

2.4 To avoid the Cartesian product phenomenon, the number of conditions must be greater than or equal to the number of connection tables - 1, eg, at least one condition is restricted for both tables. Three tables must have at least two conditions;

Note that due to the existence of the Cartesian product phenomenon, the greater the number of table connections, the lower the efficiency. Try to avoid the number of table connections.

select e.ename,d.dname from emp e,dept d where e.deptno=d.deptno;//To create an alias to improve performance sql92 syntax

2.5. Equivalent join of inner join

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

Disadvantages of sql92: The structure is unclear, the connection conditions of the table, and the conditions for further filtering in the later stage are placed behind where. The sentences are mixed.

select e.name,d.dname from emp e join dept d on e.deptno=d.depton;//sql99

//sql99 syntax select ... from a inner join b on connection conditions of a and b where filter conditions //inner can be omitted, with better readability

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

2.6. Non-equivalent join of inner join

  Case: Find out the salary grade of each employee and require the employee name, salary, and salary grade to be displayed?

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

2.7. Self-joining of inner joins

Case: Query the employee's superior leader and require the employee and corresponding leader name to be displayed? //Technique: Treat one table as two tables

select a.ename as 'employee name', b.ename as 'leaders' from emp a join emp b on a.mgr=b.empno;//Employee's leader number == leader's employee number

//Characteristics of inner connections: Complete the query of data that can match this condition.

2.8, outer connection ()

Right outer join (right join) with right

select e.ename,d.dname from emp e right join dept d on e.deptno=d.deptno;//What does right represent? It means joining the table on the right side of the keyword

It is regarded as the main table, mainly to query all the data in this table, and to query the table on the left with the association. In an outer join, two tables are connected, creating a primary and secondary relationship.

Left outer join (left join) with left

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

Any right join will be written as a left join. Any left join will have a right join.

Conclusion: The number of query results of the outer connection must be >= the number of query results of the inner connection

Case: Query the superiors of each employee and require the names of all employees and leaders to be displayed?

select a.ename as 'employee name', b.ename as 'leader name' from emp a left join emp b on a.mgr=b.empno;//The left side is the main table

2.9. How to connect three or four tables?

select ... from a join b on the connection condition of a and b join c on the connection condition of a and c right join d on the connection condition of a and d

Both inner and outer joins can be mixed in a SQL statement. They can all show up!

Case: Find out the department name and salary grade of each employee. Do you want to display the employee name, department name, salary, and salary grade?

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;

Case: Find out the department name and salary grade of each employee, as well as the superior leader. Do you want to display the employee name, leader name, department name, salary, and salary grade?

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;

3. Subquery

3.1. What is a subquery?

Select statements are nested within select statements, and the nested select statements are called subqueries.

3.2. Where are subqueries willing to appear?

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

3.3. Subquery in where clause

Case: Find the names and salaries of employees whose wages are higher than the minimum wage?

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

3.4. Subquery of from clause

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

Example: Find the confidence level of the average salary for each position.

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

3.5. Subquery of select clause (just need to understand)

Case: Find out the department name of each employee and require the employee name and department name to be displayed?

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

//It is required that the query result in the nested sub-statement must have only one result before the sub-query can be used after select.

3.6. Union merges query result sets

Case: Query employees whose job positions are manager and salesman?

select ename,job from emp where job=‘manger’or job='salesman';

select ename,job from emp where job in(‘manger','salesman');

select ename,job from emp where job=‘manger’

union

select ename,job from emp where job=‘saleman’;

The efficiency of union is higher. For table joins, every time a new table is connected, the number of matches satisfies the Cartesian product, which is doubled... 10*10=100 100*100=10000

But union can reduce the number of matches. In the case of reducing the number of matches, the splicing of the two result sets can also be completed. 100+100=200;

//When union merges result sets, the number of columns and data types of the two result sets must be the same.

4.limit

4.1. Limit function: take out part of the query result set, usually used in paging queries.

4.2 How to use limit?

Complete usage: limit startIndex, length (startIndex is the starting index, starting from 0 by default, length is the length)

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

select ename, sal from emp order by sal desc limit 5;//Get the first 5 items

select ename, sal from emp order by sal desc limit 0,5;//Get the first 0-5 items

 4.3. Limit in mysql is executed after order by! ! ! ! !

4.4. Remove the employees whose salary is ranked [3-5]?

select ename, sal from emp order by sal desc limit 2, 3; (2 represents the starting subscript, 3 represents the length)

4.5. Pagination

Each page displays 3 records, the first page has a limit of 0,3, the second page has a limit of 3,3, and the third page has a limit of 6,3;

Display pageSize records per page

第pageNo页:limit(pageNo-1)*pageSize ,pageSize

int pageNo=5; //Page 5

int pageSize=10;//Display 10 items per page

int startIndex=(page-1)*pageSize;

String sql=”select ...limit“+startIndex+”,“+pageSize;

5. A summary of DQL statements:

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

from>where>group by>having>select>order by>limit //Execution order

6. Table creation (table creation)

6.1. Syntax format for creating a table: (Creating a table is a DDL statement, and DDL includes create drop alter)

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

6.2 About the data types of mysql?

varchar variable character type, dynamic allocation of space, low performance, advantage, no waste of space

char allocates a fixed character length, high performance, fixed-length string, improper use, waste of space

When to use varchar and char? When the character is fixed, use char, and when the character changes, use varchar;

int is equivalent to int in java

bigint is equivalent to long in java

float single precision floating point type

double double precision floating point type

date short date type default input format 1910-12-08

datetime long date type default input format 1999-12-08 09:53:32

clob is a large character object that can store up to 4G of strings.

blob is a binary large object, specially used to store media stream data such as pictures, sounds, videos, etc. When inserting data into Bloob type fields, such as inserting pictures, videos, etc., you need to use IO streams.

How to delete a table without reporting an error: drop table if exists t_student;

6.3 Create student table?

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

6.4. Insert data (DML)

Syntax format: insert into table name (field name 1, field name 2...) values ​​(value 1, value 2...);

Note: The field names and values ​​must correspond one-to-one, and the quantities must correspond. The data types must correspond.

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

insert method to insert multiple rows of records at one time?

instert into t_user(id,name,birth,create_time) values (1,'zs','1980-10-11',now()),(2,'lisi','1981-10-11',now()),(3,'niuniu','1971-10-11',now());

Give default value when creating table

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

insert into t_student values(2,'lise','f',20,'[email protected]');//Note that if the previous field names are omitted, they are all included! , so the values ​​must also be written!

6.5. insert insert date

Formatting numbers: format(number, 'format')

select ename,format(sal,'$999,999') as sal from emp;

str_to_date: Convert the string varchar type to date type

date_format: Convert the date type into a varchar string type with a certain format.

str_to_date('String date','Date format') eg:str_to_date('01-10-1990','%m/%d/%Y')

Mysql date format: %Y year %m month %d day %h hour %i minute %s second

date_format This function can convert date type into a string in a specific format.

date_format (date type data, 'date format') eg: date_format(birth,'%m/%d/%Y')

6.6. Datetime is generally similar to date, but datetime is displayed more specifically.

There is a function in mysql that can get the current time of the system. The now() function is of datetime type.

6.7. Modify update (DML)

Syntax format:

update table name set field name 1 = value 1, field name 2 = value 2, field name 3 = value 3... where condition;

Note: No conditional restrictions will cause all data to be updated.

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

Update all? update t_user set name='abc';

6.8. Delete data delete (DML)

Grammar format? delete from table name where condition;

Note: Without conditions, all 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;//Delete all!

7. Quickly create tables?

create table emp2 as select * from emp;

Principle: Treat a query result as a new table! ! This can complete the quick copy of the table! ! The table is created and the data in the table also exists! !

insert into dept_bak select * from dept;//Rarely used!

Insert the query results into the dept_bak table.

8. Quickly delete data in the table?

8.1

delete from dept dept_back;//This way of deleting data is relatively slow and belongs to DML statement.

The principle of delete is to delete the data in the table one by one. The space will not be released and the data can be restored. The disadvantage is that the deletion efficiency is relatively low. The advantage is: it supports rollback and you can restore data if you regret it.

8.2

How does the truncate statement delete data?

This kind of deletion is relatively efficient. The table is truncated and physically deleted at one time.

The disadvantage of deletion is: rollback is not supported.

Advantages of this kind of deletion: fast.

Usage: truncate table dept_bak; (This operation is a DDL operation.)! ! ! ! Note that recovery is not possible and the user must be reminded.

9. Constraints

9.1. What are constraints? constraint (constrain five stars*****)

The role of constraints is to ensure that: the data in the table is valid! !

9.2. Types of constraints?

Non-null constraint: not null *

Uniqueness constraint: unique *

Primary key constraint: primary key (referred to as pk) *

Foreign key constraints: foreign key (fk for short) *

Check constraints: check (not supported by mysql, supported by oracle)

9.3. How to write non-empty constraints?

create table t_vip(id int,

name varchar(255) not null);

9.4. How to write unique constraints?

create table t_vip(

id int,

name varchar(255) unique,

email varchar(255));

The name field must be unique and cannot contain repeated strings, but it can be null.

The two fields are unique together.

create table t_vip(

id int,

name varchar(255) ,

email varchar(255),

unique(name,email)

);

When unique and not null are used together, they will become a primary key.

create table t_vip(

id int,

name varchar(255) not null unique ,

email varchar(255),

);

9.5. Primary key constraints (primary key, pk for short)

The primary key value is the unique identifier of each row of records, and the primary key is the ID number of each row of records! ! !

Remember: any table should have a primary key. Without a primary key, the table is invalid! !

Characteristics of the primary key: not null+unique (the primary key value cannot be NULL, and it cannot be repeated!)

What is the syntax for adding a primary key to a table?

drop table if exists t_vip;     |    drop table if exists t_vip;  

create table t_vip(               |   create table t_vip(

id int primary key,               |   id int ,

name varchar(255)           |   name varchar(255) ,

);                     | primary key(id,name)

//id is used as the primary key, or can be written separately | ); //id and name are used together as the primary key

In actual development, it is not recommended to use: composite primary key, it is recommended to use a single primary key! Because the function of the primary key value is the ID number, the meaning is sufficient.

In a table, only one primary key constraint can be added. (There can only be one primary key) It is recommended to use int bigint and char type as the primary key. It is not recommended to use varchar type.

as primary key. In actual development, it is best to use natural primary keys, because the primary keys do not need to be meaningful as long as they are not repeated.

9.6. Foreign key constraints (fk for short) are very important. Five stars*****

In order to ensure that the data of the child table is consistent with that of the parent table, foreign key constraints must be added to the child table. When deleting a table, you must first delete the child table before deleting the parent table.

create table t_class( create table t_student(

classno int primary key, no int primary key auto_increment,

classname varchar(255) name varchar(255),

); cno int,

//Parent table, foreign key syntax is as shown below foreign key(cno) references t_class(classno)

//Foreign keys can only write data of bound fields );

Note: The foreign key value can be null. The field bound to the foreign key must be unique, but it does not need to be the primary key.

---------------------------------------------------------------------------------------------------------------------------------

Guess you like

Origin blog.csdn.net/m0_55315930/article/details/121645487