Table of Contents
Connection query
Classification of the connection query
Cartesian product phenomenon
inner joins and equivalent joins
Inner join self-join
Inner join Non-equivalent connection
Outer connection
内连接和外连接的特点
多表连接
Home Database Mysql Tutorial How to solve the connection query problem in MySql

How to solve the connection query problem in MySql

May 26, 2023 pm 08:48 PM
mysql

    Connection query

    When performing a multi-table connection query, you need to specify the table to which the field belongs, which can improve query efficiency. If you do not specify the table to which the field belongs, The database will look for this field from each table.

    • e. Field name: means taking a field from the emp table

    • emp as e: The alias mechanism of the table, you can omit as and write it directly as emp e

    • Connection query: It can also be called cross-table query, which requires multiple tables to be associated to query data

    • The emp table and the dept table are combined to query the data. Get the employee name from the emp table and the department name from the dept table.

    Note: Do When connecting the query, be sure to write the associated conditions to avoid the Cartesian product phenomenon

    Classification of the connection query

    Classification based on the age of the grammar

    SQL92: The syntax that appeared in 1992

    • The shortcomings of sql92: the structure is not clear, the connection conditions of the table, and the conditions for further filtering in the later stage are all placed After where

    SQL99:The syntax that appeared in 1999 (focus on learning)

    • sql99 advantages: table The connection conditions and query conditions are separated. If you need to further filter after the connection, continue to add where later. It will be clearer when connecting multiple tables.

    Connect according to the table Classification of methods

    Inner join: equijoin, non-equijoin, self-join, inner can be omitted and generally not added

    • Table A inner join table B on association conditions

    Outer join: left outer join (left join), right outer join (right join), outer can be omitted and generally not added

    • Table A left outer join Table B on association condition

    • Table B right outer join Table A on association condition

    • Left join with The table on the left shall prevail and compared with the table on the right, any equality or inequalities with the left table will be displayed, and the right table will display the conditions that meet the conditions, and the conditions that do not meet the conditions will not be displayed (right join is just the opposite)

    • The functions that can be completed by left join can be completed by right join

    Full join, the two tables connected are both main tables and can be queried

    Cartesian product phenomenon

    When two tables are connected for query and no connection conditions are specified, the number of final query results is the product of the number of entries in the two tables. This phenomenon is called: Cartesian product phenomenon (Discovered by Descartes, this is a mathematical phenomenon)

    Avoid the Cartesian product phenomenon: add connection conditions when connecting multiple tables, and filter out records that meet this condition

    • The number of matches has not decreased during the matching process, but the number of final query results has become less because it is filtered according to the connection conditions

    • Through the Cartesian product phenomenon It can be concluded that the more the number of table connections, the lower the efficiency. Try to avoid the number of table connections

    inner joins and equivalent joins

    because the conditions are equal. So it is called an equijoin (data with equal connection conditions)

    Query the department name of each employee and display the employee name and department

    emp e and dept d tables To connect, the connection condition is: e.deptno = d.deptno

    	--sql92的缺点:结构不清晰,表的连接条件,和后期进一步筛选的条件,都放到了where后面
    
    	select 
    		e.ename,d.dname
    	from
    		emp e, dept d
    	where
    		e.deptno = d.deptno;
    		
    	--sql99优点:表连接的条件是独立的,连接之后,如果还需要进一步筛选,再往后继续添加where		
    	select 
    		e.ename,d.dname
    	from
    		emp e
    	--inner可以省略(带着inner可读性更好)
    	(inner) join
    		dept d
    	on
    		e.deptno = d.deptno;
    Copy after login

    Inner join self-join

    Because there is only one table connection, the specific query method is to treat one table as The two tables connect themselves, so it becomes a self-join

    Query the employee’s superior leader and require the employee name and the corresponding leader name to be displayed

    One table is viewed as two Table, emp e represents the employee table, and emp m also represents the leader table

    Connection conditions: e.mgr = m.empno employee’s leader number = leader’s employee number

    --SQL92
    select e.ename, m.ename from emp e, emp m where e.mgr=m.empno;
    
    --SQL99
    select 
    	a.ename as '员工名', b.ename as '领导名'
    from
    	emp e
    join
    	emp m
    on
    	e.mgr = m.empno;
    Copy after login

    Inner join Non-equivalent connection

    Because the connection condition is not an equivalence relationship, it is called non-equivalent connection

    Displays employee information with a salary greater than 2000, and displays the name of the department to which they belong

    --采用 SQL92 语法
    select 
    	e.ename, e.sal, d.dname 
    from 
    	emp e, dept d 
    where 
    	e.deptno=d.deptno and e.sal > 2000;
    	
    --采用 SQL99 语法
    select 
    	e.ename, e.sal, d.dname 
    from 
    	emp e 
    (inner) join 
    	dept d 
    on 
    	e.deptno=d.deptno 
    where 
    	e.sal>2000;
    Copy after login

    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
    (inner) join
    	salgrade s
    on
    	e.sal between s.losal and s.hisal;
    Copy after login

    Outer connection

    Outer connection Connection: In the outer connection, the connection between the two tables creates a primary and secondary relationship. The main query is the data of the primary table, and the secondary table is queried with the association. That is, if the other party has no records matching my primary table, then the default other party is null, outer Keywords can be omitted

    • Right outer join: The one with right is a right outer join, which means that the table to the right of the join keyword is regarded as the main table, mainly to combine this All the data in the table are queried, and the table on the left is queried with the association

    • Left outer join: The one with left t is a left outer join, which means that the table to the left of the join keyword will be Treat it as the main table, mainly to query all the data in this table, and query the table on the right with the association

    **Note: Any right join has a left join Writing method, any left connection has a right connection writing method**

    查询每个员工的上级领导,要求显示所有员工的名字和领导名 , 如果某个员工没有领导 , 那么该员工也必须显示出来

    --左连接
    select 
    	a.ename as '员工名', b.ename as '领导名'
    from
    	emp a
    left (outer) join
    	emp b
    on
    	a.mgr = b.empno; 
    
    --右连接
    select 
    	a.ename as '员工名', b.ename as '领导名'
    from
    	emp b
    right (outer) join
    	emp a
    on
    	a.mgr = b.empno;
    Copy after login

    内连接和外连接的特点

    内连接:A表和B表连接,A和B两张表没有主次关系是平等的 , 查询时只是将能够匹配上连接条件的数据查询出来 , 即如果没有匹配的就查询不出来 , inner关键字可以省略

    外连接: 在外连接当中,两张表连接产生了主次关系 , 主要查询的是主表的数据 , 捎带着关联查询次表 , 即如果对方没有记录和我主表匹配 , 那么默认对方是null , outer关键字可以省略

    注意: 区分内外连接的办法是通过 right 和 left 关键字 , 不是通过 inner 和 outer 因为它们都可以省略 , 并且外连接的查询结果条数一定是大于等于内连接的查询结果条数

    显示员工信息,并显示所属的部门名称

    select 
    	e.ename,d.dname
    from
    	emp e
    join
    	dept d
    on
    	e.deptno = d.deptno;
    Copy after login

    How to solve the connection query problem in MySql

    显示员工信息,并显示所属的部门名称,如果某一个部门没有员工,那么该部门也必须显示出来

    --外连接(右外连接)
    select 
    	e.ename,d.dname
    from
    	emp e 
    --outer是可以省略的,带着可读性强
    --right代表什么:表示将join关键字右边的这张表看成主表,主要是为了将这张表的数据全部查询出来,捎带着关联查询左边的表
    right (outer) join 
    	dept d
    on
    	e.deptno = d.deptno;
    
    
    --外连接(左外连接)
    select 
    	e.ename,d.dname
    from
    	dept d 
    --outer是可以省略的,带着可读性强
    left (outer) join 
    	emp e
    on
    	e.deptno = d.deptno;
    Copy after login

    How to solve the connection query problem in MySql

    多表连接

    一条SQL中内连接和外连接可以混合 , 都可以出现

    --表示一: a 和 b 进行内连接 , a 和 c 进行内连接 , a 和 d 进行右外连接(推荐)
    
    --表示二: a 和 b 的内连接结果去内连接 c 的结果再去右外连接 d
    select 
    	...
    from
    	a
    join
    	b
    on
    	a和b的连接条件
    join
    	c
    on
    	a和c的连接条件
    right join
    	d
    on
    	a和d的连接条件
    Copy after login

    找出每个员工的部门名称以及工资等级,要求显示员工名、部门名、薪资、薪资等级

    	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;
    Copy after login

    查询结果

    	+--------+---------+------------+-------+
    	| ename  | sal     | dname      | grade |
    	+--------+---------+------------+-------+
    	| SMITH  |  800.00 | RESEARCH   |     1 |
    	| ALLEN  | 1600.00 | SALES      |     3 |
    	| WARD   | 1250.00 | SALES      |     2 |
    	| JONES  | 2975.00 | RESEARCH   |     4 |
    	| MARTIN | 1250.00 | SALES      |     2 |
    	| BLAKE  | 2850.00 | SALES      |     4 |
    	| CLARK  | 2450.00 | ACCOUNTING |     4 |
    	| SCOTT  | 3000.00 | RESEARCH   |     4 |
    	| KING   | 5000.00 | ACCOUNTING |     5 |
    	| TURNER | 1500.00 | SALES      |     3 |
    	| ADAMS  | 1100.00 | RESEARCH   |     1 |
    	| JAMES  |  950.00 | SALES      |     1 |
    	| FORD   | 3000.00 | RESEARCH   |     4 |
    	| MILLER | 1300.00 | ACCOUNTING |     2 |
    	+--------+---------+------------+-------+
    Copy after login

    找出每个员工的部门名称以及工资等级,还有上级领导,要求显示员工名、领导名、部门名、薪资、薪资等级

    	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;
    Copy after login

    查询结果

    	+--------+---------+------------+-------+-------+
    	| ename  | sal     | dname      | grade | ename |
    	+--------+---------+------------+-------+-------+
    	| SMITH  |  800.00 | RESEARCH   |     1 | FORD  |
    	| ALLEN  | 1600.00 | SALES      |     3 | BLAKE |
    	| WARD   | 1250.00 | SALES      |     2 | BLAKE |
    	| JONES  | 2975.00 | RESEARCH   |     4 | KING  |
    	| MARTIN | 1250.00 | SALES      |     2 | BLAKE |
    	| BLAKE  | 2850.00 | SALES      |     4 | KING  |
    	| CLARK  | 2450.00 | ACCOUNTING |     4 | KING  |
    	| SCOTT  | 3000.00 | RESEARCH   |     4 | JONES |
    	| KING   | 5000.00 | ACCOUNTING |     5 | NULL  |
    	| TURNER | 1500.00 | SALES      |     3 | BLAKE |
    	| ADAMS  | 1100.00 | RESEARCH   |     1 | SCOTT |
    	| JAMES  |  950.00 | SALES      |     1 | BLAKE |
    	| FORD   | 3000.00 | RESEARCH   |     4 | JONES |
    	| MILLER | 1300.00 | ACCOUNTING |     2 | CLARK |
    	+--------+---------+------------+-------+-------+
    Copy after login

    The above is the detailed content of How to solve the connection query problem in MySql. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

    You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

    MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

    How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

    Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

    MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

    MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

    Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

    MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

    Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

    Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

    How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

    The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

    How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

    Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

    See all articles