search
HomeBackend DevelopmentPHP TutorialParse the difference between using on and where to filter mysql left(right) join_PHP tutorial

There is a question about whether there is a difference in the data queried between on and where using the left(right)join filter condition in mysql in mysql query.
You may not see any problems just by looking at the two keywords. Let's use actual examples to see if there is any difference.

For example, there are two table structures
Table structure 1

Copy code The code is as follows:

drop table if EXISTS A;
CREATE TABLE A (
ID int(1) NOT NULL,
PRIMARY KEY (ID)
) ENGINE= MyISAM DEFAULT CHARSET=latin1; The code is as follows:

drop table if EXISTS B; CREATE TABLE B ( ID int(1) NOT NULL,
PRIMARY KEY (ID)
) ENGINE= MyISAM DEFAULT CHARSET=latin1;
Insert data into table 1

Copy code

The code is as follows:


insert into A values ​​( 1 );
insert into A values ​​( 2 );
insert into A values ​​( 3 ); insert into A values ​​( 4 );
insert into A values ​​( 5 );
insert into A values ​​( 6 );
Table 2 Insert data


Copy code

The code is as follows:


insert into B values ​​(1);
insert into B values ​​(2);
insert into B values ​​(3) ;
After completion, the data in tables A and B are as follows:



Statement 1


Copy code

The code is as follows:

select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID where B.ID


Statement 2

Copy code
The code is as follows:


select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID and B .ID

Are the query results of the above two statements consistent?
Anyway, I didn’t notice any difference between the two queries [I’ve never written SQL like this before].
Let’s take a look at the actual results
Query results of statement 1

The query result of statement 2 is:

Found a difference between the two queries.

Why there is a difference? This is related to the on and where query order.

We know that the execution order of standard query keywords is from->where->group by->having->order by[I don’t remember clearly]

left join is in the from range class, so the table is first filtered by the on condition, and then the left join is done on the two tables.

For where, the left join results are filtered again.

The query process of the first sql statement is as follows:
1: First left join

Copy code The code is as follows :

select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID

The query results are as follows


2: Filter out B.ID, that is, BID

This is the result we saw above.

The query process of the second sql statement is equivalent to:

1: First selecting the table according to the on condition is equivalent to filtering table B first:

2: Then perform a left join on the query result and table A. This is why we see that the sql of the second query retains table A.
When using ON and where, you must pay attention to the place:
(1): The filtering conditions behind ON are mainly for association tables [and for Main table brush selection conditions are not applicable].
For example

Copy code The code is as follows:

select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID and A.ID = 3

The query results of this for


It’s quite surprising that the result is different from what we expected, and the data with AID=3 was filtered out.

But we also found that the values ​​corresponding to AID 1 and 2 in AID and are NULL, and the associated table only takes values ​​that meet the filtering conditions of table A.

That is, when the main table condition is after on, the attached table only takes the values ​​that meet the main table selection conditions, and the main table is still a rounded table.

(2): The filtering conditions for the main table should be placed after where, not after ON

(3): We need to treat association tables differently. If you need to query conditions before connecting, you should put the query part

Place behind on.

If you want to filter after the connection is completed, you should place the condition after where

(4): For related tables, we can actually do a subquery first and then join
So the second sql is equivalent to

Copy code The code is as follows:
select A.ID as AID, B1.ID as BID
from A left join (select B.ID from B where B.ID
All the above have been tested on mysql5.1

http://www.bkjia.com/PHPjc/327641.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327641.htmlTechArticleThere is such a problem. Mysql query uses the left(right)join filter condition in mysql to query on and where. Are there any differences in the data? You may not be able to see any problems just by looking at the two keywords. ...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft