[英]I want to join to a table, but include All records if the table being joined to is a certain ID
I want to join to a table, but include All records if the table being joined to is a certain ID.我想加入一个表,但如果加入的表是某个 ID,则包括所有记录。
I have a list of records with a type_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
Record to type is one to one, user to type is one to one, and the "Type" on a record has to be 1 or 2. User can be 1, 2 or 3. The way this would go with a normal join is记录类型是一对一,用户类型是一对一,记录上的“类型”必须是 1 或 2。用户可以是 1、2 或 3。使用普通连接的 go 的方式是
select * from record r
inner join user u on u.type_id = r.type_id
But now I need to factor in that "All" type, and basically just ignore the join/return all results if the user's type is 3.但是现在我需要考虑那个“All”类型,如果用户的类型是 3,基本上只是忽略加入/返回所有结果。
I hope this helps you:我希望这可以帮助你:
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.