简体   繁体   中英

One to Many Relationship with IN clause not giving all the many side values

I have below One to Many Relationship Tables.

| event_id (PK) | event_date | event_location |
|---------------|------------|----------------|
| 1             | 01/01/2018 | Miami          |                
| 2             | 02/04/2018 | Tampa          | 

and

| performer_id (PK) | event_id (FK) | genre |
|-------------------|---------------|-------|
| 1                 | 1             |  A    |
| 2                 | 1             |  B    |
| 3                 | 2             |  A    |

when I pass A genre to the IN clause (where in(A) I want Below

| event_id (PK) | event_location |genre|
|---------------|----------------|-----|
| 1             | Miami          |A    |
| 1             | Miami          |B    |
| 2             | Tampa          |A    |

Thank you in advance.

First you need to get the list of event_id's based on the genre and then select based on the list of event_id's from the joined tables.

Select * from 
(Select t1.event_id, t1.event_location, t2.genre
From Table_1 as t1
Inner Join table_2 as t2 on t1.event_id = t2.event_id) as output_table
Where event_id In (Select event_id From Table_2  where genre In ('A'))

Common Table Expressions should be better.

With cte1 as (Select event_id From Table_2  where genre In ('A')),

cte2 as (Select t1.event_id, t1.event_location, t2.genre
From Table_1 as t1
Inner Join table_2 as t2 on t1.event_id = t2.event_id)

Select * from cte2 
Inner Join cte1 on cte1.event_id = cte2.event_id

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