Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Union als Unterabfrage 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

Beachten Sie, dass MySQL kann Index Merge verwenden und Sie können Ihre Abfrage wie folgt umschreiben:

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

, was effizienter ist, wenn Sie die folgenden Indizes haben:

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