2

申し訳ありませんが、これは少し頭痛の種です。例から始めましょう:

テーブル:

TownCountry

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

ReFData

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

どんな助けでも大歓迎です。

4

3 に答える 3

0

結合している列に一致するものがない場合でも行を保持したい場合は、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

于 2011-07-16T22:14:31.607 に答える
0

実際には結合を行っていないので、外部結合(つまり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;

編集済み:「 andc.Record =2」をjoin句に追加しました。この小さなトリックは良いものです-それは状態を保持しますが、結合された行を必要としません

于 2011-07-16T23:05:03.523 に答える
0

ここでの問題は、Translationテーブルに空白のraw値のエントリがないことです。その結果、Translationテーブルには一致するものがないため、行は返されません。

この特定の問題は、Translationテーブルに行を追加するか、より正確には、unionを使用して行を追加することで解決できます。

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 Love、Wing

于 2011-07-17T17:23:09.947 に答える