当前位置:网站首页>[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
SELECT
andWHERE
Aliases 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
n
Multiple tables realize the query of multiple tables , At leastn-1
Connection 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;
边栏推荐
- China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
- @JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
- Chrome浏览器的crash问题
- What is CSRF (Cross Site Request Forgery)?
- LeetCode:236. 二叉树的最近公共祖先
- 如何有效地进行自动化测试?
- sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
- Delay initialization and sealing classes
- Deep analysis of C language data storage in memory
- Trying to use is on a network resource that is unavailable
猜你喜欢
win10系统中的截图,win+prtSc保存位置
PC easy to use essential software (used)
704 二分查找
swagger设置字段required必填
JVM quick start
Sublime text using ctrl+b to run another program without closing other runs
Excellent software testers have these abilities
Esp8266-rtos IOT development
LeetCode:498. 对角线遍历
TP-LINK enterprise router PPTP configuration
随机推荐
[embedded] cortex m4f DSP Library
电脑清理,删除的系统文件
What is CSRF (Cross Site Request Forgery)?
游戏解包的危害及资源加密的重要性
POI add write excel file
Leetcode: Sword finger offer 42 Maximum sum of continuous subarrays
LeetCode:673. 最长递增子序列的个数
深度剖析C语言数据在内存中的存储
704 binary search
China vanadium battery Market Research and future prospects report (2022 Edition)
What are the common processes of software stress testing? Professional software test reports issued by companies to share
Roguelike游戏成破解重灾区,如何破局?
ROS编译 调用第三方动态库(xxx.so)
Excellent software testers have these abilities
Deep anatomy of C language -- C language keywords
gcc动态库fPIC和fpic编译选项差异介绍
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
Current situation and trend of character animation
LeetCode:221. 最大正方形
Promise 在uniapp的简单使用