0

2 つのテーブル (table1 と table2 と呼びます) に参加しようとしていますが、一致ごとに 1 つのエントリしか返されません。table2 には、'y'、'n'、または 'null' のいずれかである 'current' という列があります。2 つのテーブルを結合したままにし、「y」インスタンスと「null」インスタンスを取得するために where 句を配置しました。これらは簡単です。「n」のみを持つ行に結合する行を取得して、「none」または「null」のインスタンスを 1 つ返すには、助けが必要です。ここに例があります

テーブル 1 ID
1
2
3

table2
ID | テーブル1ID | 現在の
1 | 1 | y
2 | 2 | ヌル
3 | 3 | n
4 | 3 | n
5 | 3 | n

現在のクエリは table1.ID=table2.table1ID で結合され、where 句 (where table2.current = 'y' または table2.current = 'null') がありますが、'y' がなく、値は「null」ではありません。

私のようにテーブルに参加するが、このように table1 から 3 つのレコードすべてを取得するクエリを誰かが思いつくことができますか?

クエリ リターン

ID | テーブル2ID | 現在の
1 | 1 | y
2 | null | null | ヌル
3 | 3 | null またはなし

4

3 に答える 3

1

まず、「null」値は実際には文字列であり、DB 値 NULL ではないと想定しています。その場合、以下のクエリが機能するはずです (ON サブ句の内側に where 基準が含まれていることに注意してください)。

select 
table1.ID as ID
,table2.ID as table2ID
,table2.current 
from table1 left outer join table2 
on (table2.table1ID = table1.ID and 
(table2.current in ('y','null'))

これが機能する場合は、「null」文字列値を別のものに変更することを強くお勧めします。これは完全に誤解を招くためです...あなたまたは他の開発者は、将来これをデバッグする時間を失うことになります。

「null」が実際に null 値を参照している場合は、上記のクエリを次のように変更します。

select 
table1.ID as ID
,table2.ID as table2ID
,table2.current 
from table1 left outer join table2 
on (table2.table1ID = table1.ID and 
(table2.current = 'y' or table2.current is null))
于 2009-12-14T20:47:37.207 に答える
0

table1id = 3 の table2 の 3 つの行のうち、どれが必要かを決定する必要があります。

3 | 3 | n
4 | 3 | n
5 | 3 | n

基準は何ですか?

于 2009-12-14T20:47:34.570 に答える
0
select t1.id
     , t2.id
     , case when t2.count_current > 0 then
           t2.count_current 
       else
           null
       end as current
from table1 t1
left outer join
(
  select id
  , max(table1id)
  , sum(case when current = 'y' then 1 else 0 end) as count_current
  from table2
  group by id
) t2
on t1.id = t2.table1id

ただし、justsomebody が指摘したように、テーブル 2 に「y」を含む複数の行があると、これは期待どおりに機能しない可能性があります。

于 2009-12-14T20:47:51.920 に答える