search
HomeDatabaseMysql TutorialHow to solve the connection query problem in 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;

    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;

    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;

    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;

    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;

    内连接和外连接的特点

    内连接: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;

    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;

    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的连接条件

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

    	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;

    查询结果

    	+--------+---------+------------+-------+
    	| 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 |
    	+--------+---------+------------+-------+

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

    	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;

    查询结果

    	+--------+---------+------------+-------+-------+
    	| 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 |
    	+--------+---------+------------+-------+-------+

    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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 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.

    The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

    Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 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.

    Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

    InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

    What are common causes of poor MySQL query performance?What are common causes of poor MySQL query performance?Apr 12, 2025 am 12:11 AM

    The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

    When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

    In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

    How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

    To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

    MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

    MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

    See all articles

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version