search
HomeDatabaseSQLSolving SQL problems will definitely take your understanding of MySQL one step further!

SQL Tutorial This column introduces how to understand MySQL more effectively

Solving SQL problems will definitely take your understanding of MySQL one step further!

##Recommended (free): SQL tutorial

The attribute table (product_props) structure is as follows

Data volume is more than 800W

Field nameTypeDescriptionidintidpn_idintAttribute typepv_idintAttribute valueproduct_idintProduct ID
There is a one-to-many relationship between product_id, pn_id, and pv_id.

The data is similar to this:

product_idpn_idpv_id109705 (Model) 135 (Apple 9) 1097011 (Memory) 23 (512G)1097010 (Color)17 (Local gold)109708 (Network)6(5G)109805135109801124 (1024G) ##10980
10 16 (Aurora Blue)
The product table (product) structure is as follows

data Amount above 40W

Field nameproduct_idtype_idbrand_idmodel_idstatusThe data is similar to the following:
Type Description
int product_id
int typeid
int brandid
int Model id
tinyint status

product_id109701098010981
type_id brand_id model_id status
1(Mobile) 1(Apple) 1(Iphone8) 1(Normal)
1(Mobile) 1(Apple) 1(Iphone8X) 3 (Sold)
1(Mobile) 1(Apple) 1(Iphone8XP) 1(Normal)
Problem

Find out the model number is

Apple 9

At the same time, the memory is 512G, color is local gold, status is normal, the total number of products is , ps: attribute conditions may exceed 10 Group.
Requirements

Performance comes first, avoid aggregate functions, etc.

Performance ranking of solutions to the original problem

Exist scheme from @Kamicloud
  1. SELECT 
        sql_no_cache `product_id`
    FROM
        `zx_tests` AS a
    WHERE
        `pn_id` = 101 AND `pv_id` = 59
            AND EXISTS( SELECT 
               sql_no_cache  *
            FROM
                `zx_tests`
            WHERE
            a.product_id = product_id and
                `pn_id` = 101 AND `pv_id` = 171);
    
        2 组条件下 0.657,3 组 0.695,4 组 0.759,5 组 0.743 (单独查属性表)
Subquery scheme from @Elijah_Wang
  1. SELECT `product_id` FROM `product` WHERE `pn_id` = 5 AND `pv_id` = 135 AND `product_id` IN (SELECT `product_id` FROM `product` WHERE `pn_id` = 11 AND `pv_id` = 23);
    
        2 组条件下 0.729,3 组 0.75,4 组 0.730,5 组 0.757 (新问题之前)
Performance ranking after new questions

Subquery plan from @Elijah_Wang
  1.     select SQL_NO_CACHE count(1) from pdi_product a join  (
            SELECT
                 distinct product_id
            FROM
                `product_props` 
            WHERE
                `pn_id` = 5 
                AND `pv_id` = 127
                AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 11 AND `pv_id` = 22 ) 
                AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 10 AND `pv_id` = 18 ) 
                AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 8 AND `pv_id` = 6 )  
                AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 9 AND `pv_id` = 1 )
                ) b on a.product_id = b.product_id 
                where  a.status = 1;
  2. It takes 1.5-1.56 (range of 10 executions)

expain analysis:

        select SQL_NO_CACHE count(1) from pdi_product a 
            where  a.status = 1 and a.product_id in (SELECT
             distinct product_id
        FROM
            `product_props` 
        WHERE
            `pn_id` = 5 
            AND `pv_id` = 127
            AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 11 AND `pv_id` = 22 ) 
            AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 10 AND `pv_id` = 18 ) 
            AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 8 AND `pv_id` = 6 )  
            AND `product_id` IN ( SELECT  `product_id` FROM `product_props` WHERE `pn_id` = 9 AND `pv_id` = 1 ))
SQL 性能实战来了,机不可失! takes 0.69-0.72 (range of execution 10 times)

explain analysis:

  • SQL 性能实战来了,机不可失!
exist solution from @Kamicloud
  1.     SELECT SQL_NO_CACHE
                count(1) 
            FROM
                product a
            WHERE
                a.STATUS = 1 
                AND a.product_id IN (
            SELECT DISTINCT
                `product_id` 
            FROM
                `product_props` AS a 
            WHERE
                a.`pn_id` = 5 
                AND a.`pv_id` = 127 
                AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 11 AND `pv_id` = 22 ) 
                AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 10 AND `pv_id` = 18 ) 
                AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 9 AND `pv_id` = 1 ) 
                AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 8 AND `pv_id` = 6 ) 
                );
  2. It takes 5.7-5.85 (range of execution 10 times)

explain analysis:

    SELECT SQL_NO_CACHE
        count(1) 
    FROM
        pdi_product a
        join (SELECT DISTINCT
        `product_id` 
    FROM
        `product_props` AS a 
    WHERE
        a.`pn_id` = 5 
        AND a.`pv_id` = 127 
        AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 11 AND `pv_id` = 22 ) 
        AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 10 AND `pv_id` = 18 ) 
        AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 9 AND `pv_id` = 1 ) 
        AND EXISTS ( SELECT product_id FROM `product_props` WHERE a.product_id = product_id AND `pn_id` = 8 AND `pv_id` = 6 ) ) b
    on a.product_id = b.product_id
    WHERE
        a.STATUS = 1
SQL 性能实战来了,机不可失!It takes 5.7-6.0 (range of execution 10 times)

explain analysis:

SQL 性能实战来了,机不可失!

#It can be seen that if you simply check the attribute table, the speed of the first position is the fastest, but when you check the product status, the speed is not as good as the subquery.

After explain analysis, the reason why the first subquery is fast is because its SQL is simple and the select_type is simple.

Regardless of join or exists method, select_type is mostly DERIVED and DEPENDENT SUBQUERY.

Related free learning recommendations:

mysql video tutorial

The above is the detailed content of Solving SQL problems will definitely take your understanding of MySQL one step further!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
SQL: The Commands, MySQL: The EngineSQL: The Commands, MySQL: The EngineApr 15, 2025 am 12:04 AM

SQL commands are divided into five categories in MySQL: DQL, DDL, DML, DCL and TCL, and are used to define, operate and control database data. MySQL processes SQL commands through lexical analysis, syntax analysis, optimization and execution, and uses index and query optimizers to improve performance. Examples of usage include SELECT for data queries and JOIN for multi-table operations. Common errors include syntax, logic, and performance issues, and optimization strategies include using indexes, optimizing queries, and choosing the right storage engine.

SQL for Data Analysis: Advanced Techniques for Business IntelligenceSQL for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AM

Advanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.

MySQL: A Specific Implementation of SQLMySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AM

MySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.

SQL: Making Data Management Accessible to AllSQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AM

SQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab

SQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeSQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeApr 11, 2025 am 12:04 AM

SQL indexes can significantly improve query performance through clever design. 1. Select the appropriate index type, such as B-tree, hash or full text index. 2. Use composite index to optimize multi-field query. 3. Avoid over-index to reduce data maintenance overhead. 4. Maintain indexes regularly, including rebuilding and removing unnecessary indexes.

How to delete constraints in sqlHow to delete constraints in sqlApr 10, 2025 pm 12:21 PM

To delete a constraint in SQL, perform the following steps: Identify the constraint name to be deleted; use the ALTER TABLE statement: ALTER TABLE table name DROP CONSTRAINT constraint name; confirm deletion.

How to set SQL triggerHow to set SQL triggerApr 10, 2025 pm 12:18 PM

A SQL trigger is a database object that automatically performs specific actions when a specific event is executed on a specified table. To set up SQL triggers, you can use the CREATE TRIGGER statement, which includes the trigger name, table name, event type, and trigger code. The trigger code is defined using the AS keyword and contains SQL or PL/SQL statements or blocks. By specifying trigger conditions, you can use the WHERE clause to limit the execution scope of a trigger. Trigger operations can be performed in the trigger code using the INSERT INTO, UPDATE, or DELETE statement. NEW and OLD keywords can be used to reference the affected keyword in the trigger code.

How to add index for SQL queryHow to add index for SQL queryApr 10, 2025 pm 12:15 PM

Indexing is a data structure that accelerates data search by sorting data columns. The steps to add an index to an SQL query are as follows: Determine the columns that need to be indexed. Select the appropriate index type (B-tree, hash, or bitmap). Use the CREATE INDEX command to create an index. Reconstruct or reorganize the index regularly to maintain its efficiency. The benefits of adding indexes include improved query performance, reduced I/O operations, optimized sorting and filtering, and improved concurrency. When queries often use specific columns, return large amounts of data that need to be sorted or grouped, involve multiple tables or database tables that are large, you should consider adding an index.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version