当前位置:网站首页>MySQL select query part 2
MySQL select query part 2
2022-07-25 03:27:00 【Program three two lines】
One 、 Multi-table query
1、 Overview of multi table query
1.1、 Why multi table query
Delay in executing multiple single table query statements
Data is placed in a table, resulting in field data redundancy
1.2、 Cartesian product error
select userid depname
from user ,dep
Every employee will make mistakes in all departments
The correct way is to have connection conditions
select userid depname
from user ,dep
where user.depid=dep.id
1.3、 Note for multi table query
from sql In terms of optimization , When querying multiple tables , Each field plus its table
You can alias a table , stay select and where Use aliases , Once nicknamed , stay select and where You have to use an alias , Cause or root sql Execution sequence
1.4、 Multi table query classification
angle 1: Equivalent connection 、 non-equivalence
// equivalence select userid depname from user ,dep where user.depid=dep.id // non-equivalence select userid depname from user ,dep where user.id>12
angle 2: Self join 、 Non self connecting
// Self join Query employees id And managers id select emp.id,mgr.id from employee emp ,employee mgr
angle 3: Internal connection 、 External connection
Internal connection : Merging rows of more than two tables with the same column , There are no rows in the result set that do not match one table with another
External connection : In addition to the rows that meet the connection conditions, the two tables also return the left ( Or right ) The table does not meet the conditions That's ok , This connection is called left ( Or right ) External connection . When there are no matching rows , The corresponding column in the result table is empty (NULL).
If it's a left outer connection , The table on the left of the join condition is also called Main table , The table on the right is called From the table .
If it's a right outer connection , The table on the right in the join condition is also called Main table , The table on the left is called From the table .
2、SQL92 And SQL99 Realize multi table query respectively
2.1、SQL92
stay SQL92 Used in (+) Represents the location of the slave table . That is, in the left or right outer connection ,(+) Indicates which is from the table .
Oracle Yes SQL92 Better support , and MySQL Do not support SQL92 External connection of .
# The left outer join SELECT last_name,department_name FROM employees ,departments WHERE employees.department_id = departments.department_id(+); # Right connection SELECT last_name,department_name FROM employees ,departments WHERE employees.department_id(+) = departments.department_id;
And in SQL92 in , Only the left outer connection and the right outer connection , Not full ( Or all ) External connection .
2.2、SQL99
Internal connection
SELECT Field list FROM A surface INNER JOIN B surface ON The associated condition WHERE And so on ; Be careful :inner It can be omitted
The left outer join (left OUTER JOIN)
# The query result is A SELECT Field list FROM A surface LEFT OUTER JOIN B surface ON The associated condition WHERE And so on ; Be careful :OUTER It can be omitted
Right connection (RIGHT OUTER JOIN)
FROM A surface RIGHT OUTER JOIN B surface ON The associated condition WHERE And so on ; Be careful :OUTER It can be omitted
Full outer join (FULL OUTER JOIN)
The result of full external connection = Data matching the left and right tables + There is no matching data in the left table + There is no matching data in the right table . SQL99 It supports full external connection . Use FULL JOIN or FULL OUTER JOIN To achieve . It should be noted that ,MySQL I won't support it FULL JOIN, But you can use LEFT JOIN UNION RIGHT join Instead of .
3、UNION Use
Merge query results utilize UNION keyword , You can give more than one SELECT sentence , And combine their results into a single result set . Merge when , The number of columns and data types of the two tables must be the same , And correspond to each other . each SELECT Use... Between statements UNION or UNION ALL Keyword separation .
SELECT column,... FROM table1 UNION [ALL] SELECT column,... FROM table2

Query the information of men in Chinese users and middle-aged men in American users
SELECT id,cname FROM t_chinamale WHERE csex=' male ' UNION ALL SELECT id,tname FROM t_usmale WHERE tGender='male';
4、 7 Kind of SQL JOINS The implementation of the

This is what the two tables share ( Internal connection ), intersect .
SQL sentence :
SELECT * FROM TABLEA A INNER JOIN TABLEB B ON A.KEY=B.KEY;

A Unique parts plus and A and B public Part of . Also called left outer connection .
SQL sentence :
SELECT * FROM TABLEA A LEFT JOIN TABLEB B
ON A.KEY = B.KEY;

This picture is just the opposite of the left outer connection ( Right connection ).
SQL The statement is as follows :
SELECT * FROM TABLEA A RIGHT JOIN TABLEB B
ON A.KEY = B.KEY;

This picture is A The unique part of the table .
SQL The statement is as follows :
SELECT * FROM TABLEA A LEFT JOIN TABLEB B
ON A.KEY = B.KEY
WHERE B.KEY IS NULL;

This picture is B The unique part of the table .
SQL The statement is as follows :
SELECT * FROM TABLEA A RIGHT JOIN TABLEB B
ON A.KEY B.KEY
WHERE A.KEY IS NULL;

The figure above shows all the parts of the two tables . It's the left outer connection + The right outer connection will be done once again ( Full connection ,mysql China does not support it. ,oracle Is supported by ). although MySQL Direct implementation of full connection is not supported , But it provides an indirect implementation , Namely A Table exclusive +B Table exclusive , Go again .
SQL The statement is as follows ( Normally fully connected SQL sentence ):
SELECT * FROM TABLEA A FULL OUTER JOIN TABLEB B
ON A.KEY = B.KEY;
however , stay mysql The above statement is not supported in .
MySQL Fully connected SQL sentence :
SELECT * FROM TABLEA A LEFT JOIN TABLEB B
ON A.KEY = B.KEY
UNION
SELECT * FROM TABLEA A RIGHT JOIN TABLEB B
ON A.KEY = B.KEY;
Here we explain the key words union: It means connecting and de duplication .

Empathy , This model is a total external connection .
SQL The statement is as follows :
SELECT * FROM TABLEA A FULL OUTER JOIN TABLEB B
ON A.KEY = B.KEY
WHERE A.KEY IS NULL OR B.KEY IS NULL;
stay MySQL The above statement still does not support . however , We still have an indirect implementation . In fact, No 4 And the 5 Add up and remove the weight OK 了 .
MySQL The sentences in are as follows :
SELECT * FROM TABLEA A LEFT JOIN TABLEB B
ON A.KEY = B.KEY
WHERE B.KEY IS NULL
UNION
SELECT * FROM TABLEA A RIGHT JOIN TABLEB B
ON A.KEY = B.KEY
WHERE A.KEY IS NULL;
UNOIN Keywords are the same as above .
5、 SQL99 New features of grammar
NATURAL
SQL99 stay SQL92 Provides some special syntax based on , such as NATURAL JOIN Used to represent natural connections . We can Natural connection is understood as SQL92 The equivalent connection in . It will help you automatically query the two connection tables All the same fields , Then proceed equivalence Connect . stay SQL92 In the standard :
SELECT employee_id,last_name,department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` AND e.`manager_id` = d.`manager_id`;
stay SQL99 You can write :
SELECT employee_id,last_name,department_name FROM employees e NATURAL JOIN departments d;
USING Connect
When we connect ,SQL99 Also supports the use of USING Specify... In the data table Fields with the same name Make an equivalent connection . But only with close JOIN Use it together . such as :
SELECT employee_id,last_name,department_name FROM employees e JOIN departments d USING (department_id);
Can see the connection with nature NATURAL JOIN The difference is ,USING Specifies the specific same field name , You need to USING The brackets of () Fill in the field with the same name to be specified . Use at the same time JOIN...USING Can be simplified JOIN ON Equivalent connection . It and the next Face SQL The query results are the same :
SELECT employee_id,last_name,department_name FROM employees e ,departments d WHERE e.department_id = d.department_id;
There are three ways to constrain table joins :
WHERE, ON, USING WHERE: Applicable to all associated queries
ON : And the only JOIN Use it together , Only association conditions can be written . Although Association conditions can be combined to WHERE Together with other conditions Write , But it's better to write separately .
USING: And the only JOIN Use it together , Moreover, the names of the two associated fields should be consistent in the associated table , And can only represent Related words Equal value segment
# The associated condition # Write the correlation condition in where Back SELECT last_name,department_name FROM employees,departments WHERE employees.department_id = departments.department_id; # Write the correlation condition in on Back , And the only JOIN Use it together SELECT last_name,department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id; SELECT last_name,department_name FROM employees CROSS JOIN departments ON employees.department_id = departments.department_id; SELECT last_name,department_name FROM employees JOIN departments ON employees.department_id = departments.department_id; # Write the associated fields in using() in , And the only JOIN Use it together # And the associated fields in the two tables must have the same name , And it can only mean = # Query employee name and basic salary SELECT last_name,job_title FROM employees INNER JOIN jobs USING(job_id); #n Zhang table correlation , need n-1 Two association conditions # Check the name of the employee , Basic salary , Department name SELECT last_name,job_title,department_name FROM employees,departments,jobs WHERE employees.department_id = departments.department_id AND employees.job_id = jobs.job_id; SELECT last_name,job_title,department_name FROM employees INNER JOIN departments INNER JOIN jobs ON employees.department_id = departments.department_id AND employees.job_id = jobs.job_id;
Two 、 One line function
1、 The function classification
We are using SQL When it comes to language , Not dealing directly with the language , Instead, it uses different database software , namely DBMS.DBMS There are great differences between , Much greater than the difference between different versions of the same language . actually , Only a few functions are By DBMS Supported at the same time . such as , majority DBMS Use (||) perhaps (+) To make a splice , And in the MySQL String spelling in The continuation function is concat(). Most of the DBMS Will have their own specific functions , This means adopting SQL Function code portability is very Poor , Therefore, special attention should be paid to when using functions .
From the perspective of function definition , We can divide the function into Built in functions and Custom function . stay SQL In language , It also includes Built in functions and custom functions . Built in function is a general function built in the system , Custom functions are written according to our own needs Of
MySQL The built-in functions provided are from From the perspective of function Can be divided into numerical functions 、 String function 、 Date and time functions 、 Process control function 、 Encryption and decryption functions 、 obtain MySQL Information functions 、 Aggregate functions, etc . here , I divide these rich built-in functions into two parts class : One line function 、 Aggregate functions ( Or grouping function ) .
2、 Numerical function
Basic functions

Angle and radian function

Trigonometric functions

Logarithmic function

Base conversion function

3、 String function


4、 Date and time functions
Get date Time

Date and time conversion

Get month 、 week 、 Weeks 、 Days, etc

Operation function of date

Time and second conversion function

A function that calculates the date and time


Formatting and parsing of dates



5、 Process control functions

6、 Encryption function
The encryption and decryption function is mainly used to encrypt and decrypt the data in the database , To prevent data from being stolen by others

7、 MySQL Information functions
MySQL There are some built-in functions that can be queried MySQL Functions of information , These functions are mainly used to help database developers or operation and maintenance personnel better understand Maintain the database .

8、 Other functions

3、 ... and 、 Multiline functions
边栏推荐
- List type to string type
- 2022-07-19 study notes of group 5 self-cultivation class (every day)
- mysql_ Account authorization permission recycling, account locking and unlocking, account creation and deletion
- Message queue (MQ)
- Merge sort / quick sort
- Question D: pruning shrubs
- Wechat H5 record
- Skywalking distributed link tracking, related graphics, DLJD, cat
- 55k is stable, and the recommendation system will always drop God!
- 144. Preorder traversal of binary tree
猜你喜欢

Force deduction problem 238. product of arrays other than itself

Merge sort / quick sort

Import and export using poi

Swagger key configuration items

Force deduction brush question 7. Integer inversion

C language_ Structure introduction

Direct insert sort / Hill sort

Use of stm32cubemonitor part I - data plotting and instrument display

How chemical enterprises choose digital service providers with dual prevention mechanism

2022-07-19 study notes of group 5 self-cultivation class (every day)
随机推荐
Chrome debugging skills
P100 MSSQL database penetration test of secondary vocational network security skills competition
A 20 yuan facial cleanser sold tens of thousands in seven days. How did they do it?
2022-07-19 study notes of group 5 self-cultivation class (every day)
Visio use
Performance test indicators using JMeter
Algorithmic interview questions
NVM installation and use
301. Delete invalid brackets
Detailed explanation of three factory modes
A. Subtle Substring Subtraction
[Flink] transform operator map
B. Making Towers
Import and export using poi
ECMAScript new features
Brief understanding of operational amplifier
Question B: shunzi date
What is technical support| Daily anecdotes
Sword finger offer II 041. Average value of sliding window_____ Using queue / loop array implementation
Take a note: Oracle conditional statement