当前位置:网站首页>[MySQL] multi table query
[MySQL] multi table query
2022-07-06 08:47:00 【Charming】
List of articles
Multi-table query
Multi-table query , Also known as associative queries , It means that two or more tables complete the query operation together .
Prerequisite : There is a relationship between these tables queried together ( one-on-one 、 One to many ), There must be associated fields between them , This associated field may establish a foreign key , Or you may not have established a foreign key . such as : Employee table and department table , These two tables depend on “ Department number ” Association .
1. Multi table connection caused by a case
1.1 Case description

- Check the name of the employee ’Abel’ Which city do people work in ?
SELECT *
FROM employees
WHERE last_name = 'Abel';
SELECT *
FROM departments
WHERE department_id = 80;
SELECT *
FROM locations
WHERE location_id = 2500;
Getting data from multiple tables :

Case study : Query the employee's name and department name
SELECT last_name, department_name
FROM employees, departments;

- Query results :
+-----------+----------------------+
| last_name | department_name |
+-----------+----------------------+
| King | Administration |
| King | Marketing |
| King | Purchasing |
| King | Human Resources |
| King | Shipping |
| King | IT |
| King | Public Relations |
| King | Sales |
| King | Executive |
| King | Finance |
| King | Accounting |
| King | Treasury |
...
| Gietz | IT Support |
| Gietz | NOC |
| Gietz | IT Helpdesk |
| Gietz | Government Sales |
| Gietz | Retail Sales |
| Gietz | Recruiting |
| Gietz | Payroll |
+-----------+----------------------+
2889 rows in set (0.01 sec)
- Analyze the error :
SELECT COUNT(employee_id) FROM employees;
# Output 107 That's ok
SELECT COUNT(department_id)FROM departments;
# Output 27 That's ok
SELECT 107*27 FROM dual;
We call the problem in the above multi table query as : The error of Cartesian product .
- There is a Cartesian product error , Reason for the error : The connection condition of multiple tables is missing
# Wrong implementation : Each employee matched with each department .
SELECT employee_id,department_name
FROM employees,departments; # Query out 2889 Bar record
# Wrong way
SELECT employee_id,department_name
FROM employees CROSS JOIN departments;# Query out 2889 Bar record
1.2 The cartesian product ( Or cross connect ) The understanding of the
- Cartesian product is a mathematical operation . Suppose there are two sets X and Y, that X and Y The Cartesian product of is X and Y All possible combinations of , That is, the first object comes from X, The second object comes from Y All the possibilities of . The number of combinations is the product of the number of elements in the two sets .

SQL92 in , Cartesian product is also called
Cross connect, English isCROSS JOIN. stay SQL99 It is also used in CROSS JOIN Means cross connect . Its function is to connect any table , Even if the two tables are not related . stay MySQL Cartesian product will appear in the following cases :Query employee name and department name
SELECT last_name,department_name FROM employees,departments;
SELECT last_name,department_name FROM employees CROSS JOIN departments;
SELECT last_name,department_name FROM employees INNER JOIN departments;
SELECT last_name,department_name FROM employees JOIN departments;
1.3 Case analysis and problem solving
The error of Cartesian product will occur under the following conditions :
- Omit join conditions for multiple tables ( Or related conditions )
- Connection condition ( Or related conditions ) Invalid
- All rows in all tables are interconnected
To avoid Cartesian product , Sure stay WHERE Add a valid connection condition .
After adding connection conditions , The query syntax :
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2; # Connection condition
stay WHERE Clause .
Write it correctly :
Case study : Query the employee's name and department name
SELECT last_name, department_name
FROM employees, departments
WHERE employees.department_id = departments.department_id;
When there are the same columns in the table , Prefix the column name with the table name .
If there are fields in multiple tables in the query statement , You must specify the table where this field is located .
SELECT employees.employee_id,departments.department_name,employees.department_id
FROM employees,departments
WHERE employees.`department_id = departments.department_id;
Suggest : from sql Optimization angle , It is recommended to query multiple tables , Each field is preceded by the table in which it is located .
You can start the watch Alias , stay
SELECTandWHEREAliases for tables used in .
SELECT emp.employee_id,dept.department_name,emp.department_id
FROM employees emp,departments dept
WHERE emp.department_id = dept.department_id;
- If you alias a table , Once in a SELECT or WHERE If table names are used in , You must use the alias of the table , Instead of using the original name of the table .
# The following operation is wrong :
SELECT emp.employee_id,departments.department_name,emp.department_id
FROM employees emp,departments dept
WHERE emp.department_id = departments.department_id;
- Conclusion : If there is
nMultiple tables realize the query of multiple tables , At leastn-1Connection conditions - practice : Check the employee's employee_id,last_name,department_name,city
SELECT e.employee_id,e.last_name,d.department_name,l.city
FROM employees e,departments d,locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;
边栏推荐
- 704 二分查找
- China polyether amine Market Forecast and investment strategy report (2022 Edition)
- Indentation of tabs and spaces when writing programs for sublime text
- Warning in install. packages : package ‘RGtk2’ is not available for this version of R
- Deep analysis of C language data storage in memory
- 自动化测试框架有什么作用?上海专业第三方软件测试公司安利
- The network model established by torch is displayed by torch viz
- Esp8266-rtos IOT development
- 延迟初始化和密封类
- LeetCode:236. 二叉树的最近公共祖先
猜你喜欢

Crash problem of Chrome browser

Process of obtaining the electronic version of academic qualifications of xuexin.com

Trying to use is on a network resource that is unavailable

FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战

The harm of game unpacking and the importance of resource encryption

Unsupported operation exception

Unified ordering background interface product description Chinese garbled

C语言双指针——经典题型

sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题

vb. Net changes with the window, scales the size of the control and maintains its relative position
随机推荐
sublime text的编写程序时的Tab和空格缩进问题
Hutool gracefully parses URL links and obtains parameters
Bitwise logical operator
随手记01
TCP/IP协议
Navicat premium create MySQL create stored procedure
Restful API design specification
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
TP-LINK enterprise router PPTP configuration
UnsupportedOperationException异常
The problem and possible causes of the robot's instantaneous return to the origin of the world coordinate during rviz simulation
[NVIDIA development board] FAQ (updated from time to time)
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
To effectively improve the quality of software products, find a third-party software evaluation organization
PC easy to use essential software (used)
POI add write excel file
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
Bottom up - physical layer
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
LeetCode:劍指 Offer 42. 連續子數組的最大和