在 SQL 中使用 AND 和 OR 查询搜索类别

Searching categories using AND and OR query in SQL

我想知道是否可以在 SQL 中执行 where (A OR B) AND (C) 操作?

例如,给定两个 tables
水果

+----+--------+
| id |  name  |
+----+--------+
| 1  | Apple  |
+----+--------+
| 2  | Banana |
+----+--------+
| 3  | Cherry |
+----+--------+

类别

+----+--------+------------+
| id |  name  | group_name |
+----+--------+------------+
| 1  | Red    |  colour    |
+----+--------+------------+
| 2  | Yellow |  colour    |
+----+--------+------------+
| 3  | Green  |  colour    |
+----+--------+------------+
| 4  | Round  |  shape     |
+----+--------+------------+
| 5  | Long   |  shape     |
+----+--------+------------+

和一个连接table

+----------+--------------+
| fruid_id |  category_id |
+----------+--------------+
|    1     |      1       | (Apple, Red)
+----------+--------------+
|    1     |      3       | (Apple, Green)
+----------+--------------+
|    1     |      4       | (Apple, Round)
+----------+--------------+
|    2     |      2       | (Banana, Yellow)
+----------+--------------+
|    2     |      5       | (Banana, Long)
+----------+--------------+
|    3     |      1       | (Cherry, Red)
+----------+--------------+
|    3     |      4       | (Cherry, Round)
+----------+--------------+

我想过滤所有水果,即 ('Red' OR 'Yellow') AND ('Round')。

答案应该是苹果和樱桃。

试试这个。

select  * from  fruit_category  fc
inner join  Categories c  on fc.category_id =c.id 
where     ((c.name = 'Red') or (c.name = 'Yellow'))  and    (category_id=4) 

您可以这样做:

select f.*
from fruit f join
     fruit_categories fc
     on fc.fruit_id = f.id join
     categories c
     on fc.category_id = c.id
where (c.group_name = 'color' and c.name in ('Red', 'Yellow')) or
      (c.group_name = 'shape' and c.name in ('Round))
group by f.id
having count(distinct c.group_name) = 2;  -- both color and shape match

这确实假定 "color" 在数据中的拼写一致。