문제

I'm currently playing around with building a basic storefront app for learning purposes.

I have two tables in my MySQL database "items" and "field_values" with a 1 to many relationship. There is also a fields table and a field sets table but these are not relevant to the query. A set can contain many fields and an item has one or more sets of fields.

Items

id, name

Field Values

set_id, item_id, field_1, field_2, field_3 etc..

I've built a dynamic query that allows the end user to filter down results based on the values of these fields so when 2 fields are filtered I have a query like so (pseudo)

SELECT * FROM items LEFT JOIN field_values WHERE field_1=2 and field_2=7

My question is how would I expand this to show counts for the remaining options? In other words the query above gives me one resultset but then I would also like to get the count for each of the field_3, field_4 etc values so the user knows in advance how many results they will get and so I can not present any options that would return 0 results.

I hope that makes sense.

Thanks in advance

Andy

도움이 되었습니까?

해결책

You would construct the where clause as you do now. Then do an aggregation query instead of fetching the columns:

SELECT field_1, field_2, field_3, count(*)
FROM items LEFT JOIN
     field_values
WHERE field_1 = 2 and field_2 = 7
GROUP BY field_1, field_2, field_3;

This will give all the combinations of the other values.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top