简体   繁体   English

SQL 同一列中的多个过滤器用于过滤产品

[英]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.我想要 select 产品,它们符合我的条件。

I have a table with filters and assigned products我有一张带有过滤器和指定产品的表格

filter筛选 value价值 product_id product_id
Memory Memory 2048 2048 1 1
Brand Samsung三星 1 1
Memory Memory 2048 2048 2 2
Brand Xiaomi小米 2 2

Now I need to filter Product with (filter = 'Memory' AND value = '2048') AND (filter = 'Brand' AND value = 'Samsung')现在我需要使用 (filter = 'Memory' AND value = '2048') AND (filter = 'Brand' AND value = 'Samsung') 过滤产品

This is always returning empty rows.这总是返回空行。

I am using Mariadb 10.5我正在使用 Mariadb 10.5

You can use aggregation, with a having clause being sure that all filters pass:您可以使用聚合,并使用having子句确保所有过滤器都通过:

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). count(*) = 2确保满足这两个条件(好吧,假设您在表中没有重复的行,这似乎是一个合理的假设)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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