Union as sub query MySQL

后端 未结 1 507
别跟我提以往
别跟我提以往 2021-01-13 08:06

I\'m wanting to optimize a query using a union as a sub query. Im not really sure how to construct the query though. I\'m using MYSQL 5

Here is the original query:

相关标签:
1条回答
  • 2021-01-13 08:34
    SELECT  Parts.id
    FROM    (
            SELECT  parts_id
            FROM    Parts_Category
            WHERE   Parts_Category.category_id = '508'
            UNION
            SELECT  parts_id
            FROM    Parts_Category
            WHERE   Parts_Category.main_category_id = '508'
            ) pc
    JOIN    Parts
    ON      parts.id = pc.parts_id
            AND Parts.status = 'A'
    LEFT JOIN
            Image
    ON      image.id = parts.image_id
    

    Note that MySQL can use Index Merge and you can rewrite your query as this:

    SELECT  Parts.id
    FROM    (
            SELECT  DISTINCT parts_id
            FROM    Parts_Category
            WHERE   Parts_Category.category_id = '508'
                    OR Parts_Category.main_category_id = '508'
            ) pc
    JOIN    Parts
    ON      parts.id = pc.parts_id
            AND Parts.status = 'A'
    LEFT JOIN
            Image
    ON      image.id = parts.image_id
    

    , which will be more efficient if you have the following indexes:

    Parts_Category (category_id, parts_id)
    Parts_Category (main_category_id, parts_id)
    
    0 讨论(0)
提交回复
热议问题