简体   繁体   中英

SQL Multiple filters in same columns for filtering product

I am trying to filter products from my database. I want to select products, they meet my conditions.

I have a table with filters and assigned products

filter value product_id
Memory 2048 1
Brand Samsung 1
Memory 2048 2
Brand Xiaomi 2

Now I need to filter Product with (filter = 'Memory' AND value = '2048') AND (filter = 'Brand' AND value = 'Samsung')

This is always returning empty rows.

I am using Mariadb 10.5

You can use aggregation, with a having clause being sure that all filters pass:

select product_id
from t
where (filter = 'Memory' AND value = '2048') or
      (filter = 'Brand' AND value = 'Samsung')
group by product_id
having count(*) = 2;

The count(*) = 2 is ensuring that both conditions are met (well, assuming you don't have duplicate rows in the table, which seems like a reasonable assumption).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM