简体   繁体   中英

Searching categories using AND and OR query in SQL

I wonder is it possible to do where (A OR B) AND (C) operation in SQL?

For example, given Two tables
Fruits

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

Categories

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

And a join 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)
+----------+--------------+

And I wish to filter all fruits that is ('Red' OR 'Yellow') AND ('Round').

The answer should be Apple and Cherry.

try this out.

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) 

You can do this as:

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

This does assume that "color" is spelled consistently in the data.

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