Ecco come puoi farlo:
SELECT meta_name, meta_value, COUNT(DISTINCT item_id) count
FROM meta m JOIN item_meta im
ON im.field_id = m.id
GROUP BY meta_name, meta_value
Uscita:
| META_NAME | META_VALUE | COUNT | |----------------|------------|-------| | Car Type | Coupe | 2 | | Car Type | Sedan | 1 | | Color | Black | 1 | | Color | Red | 1 | | Color | White | 1 | | Interior Color | Black | 2 | | Interior Color | Grey | 1 | | Make | BMW | 2 | | Make | Honda | 1 | | Model | 2Series | 1 | | Model | 3Series | 1 | | Model | Civic | 1 |
Ecco SQLFiddle demo
AGGIORNAMENTO:
Filtrato:
SELECT meta_name, meta_value, COUNT(DISTINCT item_id) count
FROM meta m JOIN item_meta im
ON im.field_id = m.id
WHERE item_id IN
(
SELECT i.id
FROM item_meta im JOIN items i
ON im.item_id = i.id JOIN meta m
ON im.field_id = m.id
GROUP BY i.id
HAVING MAX(meta_name = 'Make' AND meta_value = 'BMW') = 1
AND MAX(meta_name = 'Car Type' AND meta_value = 'Coupe') = 1
)
GROUP BY meta_name, meta_value;
Uscita:
| META_NAME | META_VALUE | COUNT | |----------------|------------|-------| | Car Type | Coupe | 2 | | Color | Black | 1 | | Color | White | 1 | | Interior Color | Black | 1 | | Interior Color | Grey | 1 | | Make | BMW | 2 | | Model | 2Series | 1 | | Model | 3Series | 1 |
Ecco SQLFiddle demo
AGGIORNAMENTO2:
È facile. Naturalmente invece di usare AND
in HAVING
clausola (un'auto non può essere nera e rossa contemporaneamente) devi usare OR
così
HAVING MAX(meta_name = 'Color' AND meta_value = 'Black') = 1
OR MAX(meta_name = 'Color' AND meta_value = 'Red') = 1
oppure ecco un altro modo per esprimere lo stesso intento
HAVING MAX(meta_name = 'Color' AND meta_value = 'Black') +
MAX(meta_name = 'Color' AND meta_value = 'Red') > 0
Ecco SQLFiddle demo