联盟作为子查询MySQL

前端之家收集整理的这篇文章主要介绍了联盟作为子查询MySQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想使用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 

我想要做的是用下面的union替换它((Parts_Category.category_id =’508’或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很新.

最佳答案
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可以使用索引合并,您可以重写您的查询

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)

猜你在找的MySQL相关文章