联盟作为子查询MySQL

时间:2009-07-21 14:00:29

标签: mysql union

我想使用union作为子查询来优化查询。我不确定如何构建查询。我正在使用MYSQL 5

以下是原始查询:

SELECT  Parts.id 
FROM    Parts_Category, Parts 
    LEFT JOIN Image ON Parts.image_id = Image.id 
WHERE 
( 
    (
        Parts_Category.category_id = '508' OR 
        Parts_Category.main_category_id ='508'
    ) AND 
    Parts.id = Parts_Category.Parts_id 
) AND 
Parts.status = 'A' 
GROUP BY 
    Parts.id 

我想要做的是将此( (Parts_Category.category_id = '508' OR Parts_Category.main_category_id ='508' )部分替换为下面的联合。这样我可以删除GROUP BY子句并使用直接col索引来提高性能。零件和零件类别表每个包含50万条记录,因此任何收益都会很大。

(
    SELECT * FROM
    (
        (SELECT Parts_id FROM Parts_Category WHERE category_id = '508') 
        UNION 
        (SELECT Parts_id FROM Parts_Category WHERE main_category_id = '508')
    )
    as Parts_id
)

有人能给我一些关于如何重写它的线索吗?我已经尝试了几个小时但是无法得到它,因为我只是对MySQL很新。

1 个答案:

答案 0 :(得分:4)

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

请注意,MySQL可以使用Index Merge,您可以将此查询重写为:

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

,如果您有以下索引,效率会更高:

Parts_Category (category_id, parts_id)
Parts_Category (main_category_id, parts_id)