Question: Postgres Match All array values to same column with and condition

Question

Postgres Match All array values to same column with and condition

Answers 1
Added at 2016-12-21 11:12
Tags
Question

I have table table_a with following columns

id  event_id
1   101
1   102
1   103
2   105
2   103
2   106

I want to search (101, 103) with and conditions similar to IN query with OR condition

let say id is foreign of another table event_categories having relation like this.

id      parent_id
101     null
102     101
103     101
104     null
105     104

so I want to fetch records from table_a based on AND with parent event category, OR within sub-event categories of that parent.

Attached screenshot for more clarification

enter image description here

For example "Art Galleries & Exhibits", "Festivals", "Food & Wine" with AND condition,

All sub-category of "Art Galleries & Exhibits" with OR condition "Art & Craft Workshops" OR "Art & Craft Fairs" OR "Visual Arts" if checked.

Table events

  id   
-------
 24445
 24446
 24447
 24448
 24449

event_categories table

      id  |           name           | parent_id 
-----+--------------------------+-----------
  55 | Art &  Craft Workshops   |        25
  53 | Art & Craft Fairs        |        25
  25 | Art Galleries & Exhibits |          
  14 | Carnivals                |         3
  56 | Celebrations             |         3
  64 | Chili Cook-offs          |        26
  47 | Circus                   |        13
  45 | Comedy                   |        13

Relation table events with event_categories event_id is foreign key of events table

 event_id | event_category_id 
----------+-------------------
    24590 |                 1
    24590 |                13
    24445 |                 1
    24445 |                13
    24591 |               1
Answers to

Postgres Match All array values to same column with and condition

nr: #1 dodano: 2016-12-21 11:12

First question:

SELECT id
FROM table_a
WHERE id IN (101, 103)
GROUP BY id
HAVING COUNT(DISTINCT id) = 2
Source Show
◀ Wstecz