同じ結果を返すと予想される同じクエリの2つのバージョンがありますが、結果は異なります。PostgreSQLのクエリ配置により異なる結果が発生する
クエリ1:
select * from erp_data.invoices i
left join
(select * from erp_data.invoice_extra_data where data_key = 'job_number') d
using(invoice_id)
where customer_no = '6357' and (data_key = 'job_number' or data_key is null)
and (customer_purchase_order_no ilike '%newtown%' or customer_purchase_order_no ilike '%newtown%' or customer_purchase_order_no ilike '%newton%')
and (order_date >= '2017-09-01' and order_date < '2017-11-01')
クエリ2:
select * from erp_data.invoices i
left join erp_data.invoice_extra_data d
using(invoice_id)
where customer_no = '6357' and (data_key = 'job_number' or data_key is null)
and (customer_purchase_order_no ilike '%newtown%' or customer_purchase_order_no ilike '%newtown%' or customer_purchase_order_no ilike '%newton%')
and (order_date >= '2017-09-01' and order_date < '2017-11-01')
これは、PostgreSQLは最初に参加しないように見え、その後、参加にどこ原因が適用されます。 invoice_extra_dataテーブルにインボイステーブルのすべてのアイテムにSOMETHINGがあるため、すべての請求書にdata_key = 'job_number'というものがあるわけではないので、2つのクエリが異なる結果を返します。
具体的には、data_key = 'job_number'のinvoice_extra_dataテーブルにエントリを持たない請求書は、2番目のクエリで除外されます。 「左の結合のためにそのような請求書を表示する」または「それが失敗するので、そのような請求書を拒否する」という「期待される結果」を解釈することができます。
postgresqlは、クエリのwhere部分にフィルタを適用する前に常にjoinを実行しますか?
EXPLAINの出力を見ましたか? – fvu
"EXPLAIN"は、両方のクエリで同じように見える結果を生成しました。私はクエリブラウザで "EXPLAIN"を実行し、作成した画像を見ました - 私は説明から生のテキストを見ていませんでした。 – zelinka
2つのテーブルエイリアス、 'd'と' i'を導入しました。さて、**それらを使用してください**。 – wildplasser