Mysql | Faceted search

2019-06-02 05:50发布

问题:

I have a fiddle: http://sqlfiddle.com/#!2/46a7b5/18

This request return all attributes.

|      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 |

To get searched result I have the request below:

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;

And new fiddle.

My output:

|      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 |

I'm looking for the way to get results shown below:

|      META_NAME | META_VALUE | COUNT |
|----------------|------------|-------|
|       Car Type |      Coupe |     2 |
|       Car Type |      Sedan |     0 |
|          Color |      Black |     1 |
|          Color |        Red |     0 |
|          Color |      White |     1 |
| Interior Color |      Black |     2 |
| Interior Color |       Grey |     1 |
|           Make |        BMW |     2 |
|           Make |      Honda |     0 |
|          Model |    2Series |     1 |
|          Model |    3Series |     1 |
|          Model |      Civic |     0 |

Is it possible? Thanks!

回答1:

Instead of using a subquery, you may get the values from a left join and count the distinct not null values.

SELECT meta_name, meta_value, COUNT(DISTINCT pid) count
  FROM meta m JOIN item_meta im
    ON im.field_id = m.id
LEFT JOIN (
    SELECT i.id pid
  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)
LJ ON im.item_id = LJ.pid
 GROUP BY meta_name, meta_value;