[英]I want to join to a table, but include All records if the table being joined to is a certain ID
我想加入一個表,但如果加入的表是某個 ID,則包括所有記錄。
我有一個 type_id 的記錄列表:
RECORD
id | type_id
---|---
1 | 1
2 | 1
3 | 2
TYPE
id | type_desc
---|---
1 | type1
2 | type2
3 | all
USER
id | type_id
---|---
1 | 1
2 | 3
3 | 2
記錄類型是一對一,用戶類型是一對一,記錄上的“類型”必須是 1 或 2。用戶可以是 1、2 或 3。使用普通連接的 go 的方式是
select * from record r
inner join user u on u.type_id = r.type_id
但是現在我需要考慮那個“All”類型,如果用戶的類型是 3,基本上只是忽略加入/返回所有結果。
我希望這可以幫助你:
With dtAll as (
select * from user u
where u.type_id = 3
limit 1
)
select * from record r
inner join user u on u.type_id = r.type_id or exists( select * from dtAll )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.