【问题标题】:Join tables that might not have records联接可能没有记录的表
【发布时间】:2018-05-15 14:35:24
【问题描述】:

我有两个表,tableA 有一个记录列表,tableB 有限制(如果有的话)。如果tableB 中有记录,或者如果tableB 为空,我如何加入基本上是inner join 的表?

即:

tableA
id | name 
1 | val1
2 | val2

tableB (with restrictions)
id | name | userID
1 | val1 | 123

OR tableB (no restrictions)
id | name | userID

这可能吗?我在下面的尝试:

    SELECT a.*
    FROM tableA a
    INNER JOIN (CASE WHEN select 1 from tableB = 1 THEN tableB ELSE tableA END) b
    ON a.id = b.id
where userID = XXX

EDIT:tableB上有一个检查

【问题讨论】:

  • 你的数据库引擎是什么?
  • 我正在使用 SQL 服务器
  • 您正在寻找外连接
  • 这不就是左连接吗,我还缺什么?
  • 这不是左连接,因为tableB 可能没有行。如果没有行则查询失败

标签: sql sql-server join case


【解决方案1】:

只需使用左连接

SELECT a.*
FROM tableA a
LEFT JOIN tableB b = ON a.id = b.id and b.userid = xxx

目前我没有看到任何复杂性 - 鉴于原始问题中的陈述很简单,我想知道您是否将 WHERE 谓词放在表 B 中 - 如果是,它们需要在连接的ON子句

已编辑以包含您的 where 子句已移动。

【讨论】:

  • 啊是的.. where 子句中有tableB!
  • 将该谓词移至连接 ON 条件,否则左连接会无意中起到内连接的作用(除非您允许空值)
【解决方案2】:

对于空行,您可以对两个限制使用相同的查询。 我猜你是使用SQL server

如果表 b 为空,则使用左连接拉取行

select a.id,a.name 
    from tableA a left join tableB on a.id = b.id

演示:

declare @tableA table (id int, name varchar(10))
insert into @tableA
select 1, 'name'
union all
select 2,'name1'
union all
select 3,'name2'

declare @tableb table (id int, name varchar(10))

select a.id,a.name 
from @tableA a left join @tableb b on a.id = b.id

【讨论】:

  • 我认为这不能解决我的问题。如果 tableB 为空白,我希望能够从 tableA 中提取所有内容
  • 这行不通。如果 TableB 为空,则此结果集将为空。
  • 用左连接检查
  • 左连接不起作用,因为 tableB 是空的,它不会拉任何记录
  • 你试过了吗,如果表b为空,它会从表a中提取记录
【解决方案3】:

如果tableB 为空,这将从tableA 中提取所有记录,如果不是,则仅匹配记录:

select a.id, a.name 
from tableA a
    join tableB on a.id = b.id
where exists (select 1 from tableB)
union all
select a.id, a.name 
from tableA a
where not exists (select 1 from tableB)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多