简体   繁体   English

我想加入一个表,但如果加入的表是某个 ID,则包括所有记录

[英]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.

相关问题 在联接表中选择所有不满足某些条件的记录 - Select all records don't meet certain conditions in a joined table INNER JOIN表并以CSV格式返回所有联接结果(不是单独的记录) - INNER JOIN table and return all joined results as CSV (not separate records) 复杂的sql:包括来自products表的记录,其中join的值已删除join表中设置的值 - complex sql: include records from products table where value on join has isdeleted value set in joined table SQL左联接,但不希望左表中的所有记录 - SQL Left Join but don't want all records in the left table 即使JOINed表中没有对应的记录,如何从一个表中获取所有记录? - How can I get all records from one table, even if there are no corresponding records in the JOINed table? SQL 查询连接表中的所有分组记录 - SQL query for all grouped records in joined table 如何检索连接表 SQL 的所有记录 - How to retrieve all records of joined table SQL 当其中一个联接表中缺少所有记录时,如何返回所有记录的结果? - How do I return results for all records in a joined table query when they are missing from one of the joined tables? 是否可以包含联接表中除联接一个以外的所有字段? - Is it possible to include ALL fields from joined table EXCEPT joined one? 基于2个表以及一个联接表和行的MySQL查询应按顺序包括联接数据的所有实例 - MySQL query based on 2 tables and a join table and rows should include all instances, in order, of joined data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM