sql >> Database teknologi >  >> RDS >> Mysql

Få produkter med ønskede egenskaber

De 2 filtre skal håndteres separat, da hvert filter skal se på helt forskellige poster i products_attributes_values tabel.

SELECT * FROM products
WHERE category_id IN ('6', '7', '29', '8', '9', '36')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 2
            AND value_id = '4')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 3
            AND value_id = '11')

Fra UAMoto:

Det virker, men lidt langsomt, så jeg har brugt join-aliaser, som en person fortalte mig:

"SELECT * FROM `products`
JOIN `products_attributes_values` AS pav1
ON (`pav1`.`product_id` = `products`.`id`)
JOIN `products_attributes_values` AS pav2
ON (`pav2`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND (`pav1`.`attribute_id` = '2' AND `pav1`.`value_id` = '4')
AND (`pav2`.`attribute_id` = '3' AND `pav2`.`value_id` = '11')"

Opdaterede forespørgsler til kombinationer af attributter:

SELECT * FROM products
WHERE category_id IN ('6', '7', '29', '8', '9', '36')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 2
            AND value_id IN ('4', '5'))
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 3
            AND value_id IN ('11', '62'))

eller

SELECT *
FROM `products`
    JOIN `products_attributes_values` AS pav1 ON (`pav1`.`product_id` = `products`.`id`)
    JOIN `products_attributes_values` AS pav2 ON (`pav2`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND (`pav1`.`attribute_id` = '2' AND `pav1`.`value_id` IN ('4', '5'))
AND (`pav2`.`attribute_id` = '3' AND `pav2`.`value_id` IN ('11', '62'))



  1. Gendannelse af MySQL-databaser ved geninstallation af Wamp

  2. Vigtigheden af ​​transaktionslog i SQL Server

  3. ORACLE SQL*Plus Tutorial

  4. Adskilte pgAdmin og cmd psql databaser