MySQL In cannot be rewritten using an internal connection

Source: Internet
Author: User

MySQL In cannot be rewritten using an internal connection

The original interview was carried out as an interview question ..
What MySQL In uses Exists, which is very slow...
The interviewer asked me what to do. The answer was to rewrite it with an inner connection ..
Then the interviewer smiled ..

This script has always been used ..
It wasn't until yesterday that I found out that this script was wrong.

Lab data
Create table song (
Songid int
);
Insert into song values (1), (2), (3 );

Create table song_category_relation (
Category varchar (10 ),
Songid int
);
Insert into song_category_relation values
('China', 1 ),
('China', 2 ),
('China', 3 ),
('Hot topic ', 3 );

Song is a song table
Song_category_relation is a ing table between songs and categories.
A song may have multiple categories.

Requirement.
If you know the ID of a song, find all the categories to which the song belongs, and then find all the songs under all categories.

Use In
Select * from song where songid in (
Select songid from song_category_relation where Category in
(Select Category from song_category_relation where songid = 3)
);

However, if you use an inner connection to rewrite it ..
Select * from song inner join (
Select songid from song_category_relation where Category in
(Select Category from song_category_relation where songid = 3)
) A on (a. songid = song. songid );

We can see that the results of the two methods are not the same ..
Logically, the subquery after In goes through deduplication.
After MySQL 5.6 was implemented through Exists, Semi Join optimization was adopted.

Semi Join reference:

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.