2017-02-13 9 views
0

プロジェクトには、いくつかのテーブルに関連するビジネス要件があります。次の2つのクエリオプションは、そのような場合のパフォーマンスの最適化に役立ちます。どのように選ぶべきですか? まず:デカルト積フィルタ:異なるSQLクエリの効率

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 

を第二:左外側の接続モードまたは右外側接続モード

select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id 

を教えてください。どうもありがとうございました。

+0

と同じ意味を持っていると同じ意味を持っています。あなたは詳細を教えていただけますか? – 0xCAFEBABE

+0

2つは同等ではありません。 'LEFT JOIN'は一致する' table2'行を持たない 'table1'行を返します。デカルト積はこれらの行を返しません。 – Barmar

+0

@ 0xCAFEBABE上記の2つの方法を使用して同じデータを照会しますが、どのような場合にパフォーマンスが向上するかを知りたい場合 – lpgad

答えて

0

同じ結果が得られる形式で記述する場合は、クエリアナライザが同じ*クエリプランを使用することを期待してください。 ,を使用すると、2つの異なるクエリのパフォーマンスを比較したい場合は、最も簡単な方法は、両方を実行して、どのくらい彼らを比較することですあまり明確であり、そして数十年

のために廃止されましたので、それは、使用しない,を登録しようとクエリプランを比較することで異なることを確認していますが(EXPLAIN query text hereがmysqlでクエリのプランを提供します)

「私は彼らが異なる結果を出すのは知っていますが、プログラミングでは決して賢明なことではありません。あなたは常にあなたが望む結果を正確に知るべきです。

I.e.

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 

select table1.a ,table2.b from table1 join table2 on table1.id=table2.id 

select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id 

と同じ意味を

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select table1.a , null from table1 where table1.id not in (select table2.id from table2) 

と同じ意味を持っており、あなたが使用していないフォームに参加しています

select table1.a ,table2.b from table1 right join table2 on table1.id=table2.id 

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select null, table2.b from table2 where table2.id not in (select table1.id from table1) 

そして

select table1.a ,table2.b from table1 full join table2 on table1.id=table2.id 

私は質問を理解していない

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select table1.a , null from table1 where table1.id not in (select table2.id from table2) 
union 
select null, table2.b from table2 where table2.id not in (select table1.id from table1) 
-2

2番目のクエリが高速です。それは入れ子状態を持たない。 SQLエンジンは、単一の表またはビューとして結合を処理します。

私のopenionの最初のクエリは "Forループ"として機能し、実行時間の複雑さはO(n)で、seconfクエリはSwitch Caseとして動作します。ランタイムの複雑さはO(log n)です。

+0

いずれにしても、第2のものは第1のものより優れていますか? – lpgad

+0

SQLはクエリプランのステップを実行します。 OPの2つのクエリは同様のプランを持ちます(左結合から 'join 'に変更した場合と同じです) – Caleth