【问题标题】:SELECT CASE/JOIN when no rows没有行时选择 CASE/JOIN
【发布时间】:2011-10-06 22:11:56
【问题描述】:

对不起,这个有点头疼。我将从示例开始:

表格:

城镇国家

Record |  Town  | CountryCode
-------+--------+-------------
1      | London | A1
2      | Cardiff| A2
3      | Hull   | A1
4      | Luton  | A1

参考数据

Type    |  Code   | Country
--------+---------+-------------
Country | A1      | England
Country | A2      | Wales

如果我的查询是:

select a.Town, b.Country from TownCountry a, RefData b, TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

我明白了:

London | Wales

但是,如果我将威尔士的代码更改为 A3,并保持查询不变,则结果不会返回任何行。

在威尔士是 A3 的示例中,我想要的结果是:

London | (empty)

我已经尝试过 COALESCE:

select a.Town, COALESCE(b.Country,'empty') from TownCountry a, RefData b, TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

但这没有返回任何行

我也尝试过选择大小写、左右连接,但仍然没有行。

这是我的好朋友在讨论时给我的一个更简单的例子:

城镇

Record |  Town  
-------+--------
1      | London 
2      | Cardiff
4      | Luton

select a.Town, b.Town, c.town, d.Town
from Towns a, Towns b, Towns c, Towns d
where a.Reocrd=1 and b.Reocrd=2 and c.Reocrd=3 and a.Reocrd=4

我想回来

a.Town | b.Town | c.Town | d.Town
-------+--------+--------+--------
London | Cardiff| NULL   | Luton

非常感谢任何帮助。

【问题讨论】:

  • 首先,TownCount 不是表,你朋友的代码不可能运行。复制和粘贴比打字更可靠。其次,你想要的对我来说没有意义。你能解释一下你试图解决的问题,而不是描述你是如何解决它的吗?我能想象返回伦敦的唯一合理数据是赫尔(城镇)或英格兰(国家)。
  • 抱歉,错字,应该是 TownCountry
  • 你为什么要加入 TownCountry 两次?你应该只需要一次。

标签: sql join db2 select-case


【解决方案1】:

这里的问题是翻译表没有空白原始值的条目。 结果,Translation 表中没有任何匹配项,因此不会返回任何行。

这个特殊的问题可以通过向 Translation 表中添加一行来解决,或者更准确地说,使用联合来添加行:

select a.Town, b.Country from TownCountry a, 
(select Code, Country from RefData b
union select '' as Code, 'Not found' as Country from RefData c), TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

SQL 爱, 翼

【讨论】:

  • 你为什么要这样做?外连接的重点是在另一个表中没有匹配行的情况下为您提供 NULL。
【解决方案2】:

如果您想保留行,即使您要加入的列上没有匹配项,您需要使用OUTER JOIN 而不是INNER JOIN

http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.apdv.porting.doc/doc/r0052878.html

【讨论】:

    【解决方案3】:

    真的没有进行连接,您需要外部连接(即LEFT JOIN)。

    你想要的是这样的:

    select a.Town, b.Country
    from TownCountry a
    left join RefData b on b.Code = a.CountryCode
    left join TownCountry c on c.CountryCode = b.Code and c.Record=2
    where a.Record=1;
    

    已编辑:我将“and c.Record=2”放入连接子句中。这个小技巧很好——它保留了条件,但不需要连接行

    【讨论】:

    • 为什么我没有真正做连接?为什么你有 2 个左连接?本质上,我要做的是将二维数组变成 1 行。问题是一些数据需要转换(国家代码)。如果我们要加入 RefData(即从 RefData 返回 CountryCode 中不匹配的所有内容),那么如果 RefData 和 CountryCode 之间不匹配,将从 RefData 返回什么?那么我看到的方式是,我们使用 CountryCode 的第二个实例作为对 RefData 的查找,所以如果没有匹配,可能会返回什么?
    • 我们可以用我提到的第二个例子作为例子吗?在表的第三个实例 (Towns c) 中没有匹配项,因此整个查询不返回任何行。我需要做的是返回 Null 或 Empty 字段。
    • 有一种方法——你将条件放入连接中。查看更新的答案
    猜你喜欢
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2010-09-17
    • 2020-09-05
    • 2015-07-27
    相关资源
    最近更新 更多