J'ai les tableaux suivants
table : produits
+------------+--------------------+
| product_id | name |
+------------+--------------------+
| 1 | samsung galaxy s8 |
| 2 | apple iphone 7 |
+------------+--------------------+
table : attributs
+--------------+--------------------+
| attribute_id | name |
+--------------+--------------------+
| 1 | brand |
| 2 | color |
+--------------+--------------------+
table : valeurs des attributs
+--------------------+--------------+------------+---------------------+
| attribute_value_id | attribute_id | product_id | value |
+--------------------+--------------+------------+---------------------+
| 1 | 1 | 1 | samsung |
| 2 | 2 | 1 | blue |
| 3 | 1 | 2 | apple |
| 4 | 2 | 2 | red |
+--------------------+--------------+------------+---------------------+
Et j'ai les requêtes suivantes :
Requête 1 (Fonctionne !)
SELECT
p.product_id AS product_id,
p.name AS product_name,
v.value AS attribute_value,
a.attribute_id AS attribute_id,
a.name AS attribute_name,
c.name AS attributes_category_name
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
p.product_id IN (
SELECT
p.product_id
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
(a.name = 'brand' AND (v.value = 'samsung'))
)
Requête 2 (NE FONCTIONNE PAS !)
SELECT
p.product_id AS product_id,
p.name AS product_name,
v.value AS attribute_value,
a.attribute_id AS attribute_id,
a.name AS attribute_name,
c.name AS attributes_category_name
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
p.product_id IN (
SELECT
p.product_id
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
(a.name = 'brand' AND (v.value = 'samsung'))
AND (a.name = 'color' AND (v.value = 'blue'))
)
Comme vous pouvez le constater, la différence entre les 2 requêtes se situe au niveau de la clause WHERE.
Query 1:
--------
p.product_id IN (
SELECT
p.product_id
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
(a.name = 'brand' AND (v.value = 'samsung'))
)
Query 2:
--------
p.product_id IN (
SELECT
p.product_id
FROM
products p
LEFT JOIN
attribute_values v USING (product_id)
LEFT JOIN
attributes a USING (attribute_id)
WHERE
(a.name = 'brand' AND (v.value = 'samsung'))
AND (a.name = 'color' AND (v.value = 'blue'))
)
Je recherche dans la première requête uniquement la marque > samsung, dans la deuxième requête la marque > samsung AND couleur > bleu.
Quelqu'un sait-il pourquoi ma deuxième requête ne fonctionne pas ?