【问题标题】:One to Many Relationship with IN clause not giving all the many side values与 IN 子句的一对多关系未给出所​​有多边值
【发布时间】:2022-01-23 20:21:37
【问题描述】:

我有以下一对多关系表。

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

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

当我将 A 类型传递给 IN 子句时(我想要在下面的 in(A) 中

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

提前谢谢你。

【问题讨论】:

  • 这是一个JOIN 问题。 w3schools.com/sql/sql_join.asp。提示:您需要在 event_id 上加入
  • 请用您正在使用的 SQL 查询更新您的问题
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: sql postgresql one-to-many


【解决方案1】:

首先您需要根据流派获取 event_id 列表,然后根据连接表中的 event_id 列表进行选择。

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'))

公用表表达式应​​该更好。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2018-03-16
    • 2021-09-26
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多