以下のようなクエリがあります。
select
a.id, a.title, a.description
from
my_table_name as a
where
a.id in (select id from another_table b where b.id = 1)
私の質問は、パフォーマンスを損なうことなく、where 句でサブクエリを回避し、from 句自体で使用できる方法はありますか?
以下のようなクエリがあります。
select
a.id, a.title, a.description
from
my_table_name as a
where
a.id in (select id from another_table b where b.id = 1)
私の質問は、パフォーマンスを損なうことなく、where 句でサブクエリを回避し、from 句自体で使用できる方法はありますか?
これまでに与えられた両方の回答は、一般的なケースでは正しくありません (データベースには、特定のケースで正しいことを保証する一意の制約がある場合があります)。
another_table
同じ行が複数ある場合id
は、バージョンINNER JOIN
に存在しない重複が返されます。IN
でそれらを削除しようとすると、列自体に重複がDISTINCT
ある場合にセマンティクスが変わる可能性があります。my_table_name
一般的な書き直しは
SELECT a.id,
a.title,
a.description
FROM my_table_name AS a
JOIN (SELECT DISTINCT id
FROM another_table
WHERE id = 1) AS b
ON b.id = a.id
この書き換えのパフォーマンス特性は、実装に依存します。
結合として表現するには:
select distinct
a.id, a.title, a.description
from my_table_name as a
join another_table b on b.id = a.id
where b.id = 1
の使用はdistinct
、another_table が同じ ID を複数回持っている場合に同じ結果を生成するためのもので、同じ行が複数回返されることはありません。
注: my_table_name の ID、名前、および説明の組み合わせが一意でない場合、このクエリは元のクエリのように重複を返しません。
同じ結果が得られることを保証するには、another_table の ID が一意であることを確認する必要があります。これを結合として行うには:
select
a.id, a.title, a.description
from my_table_name as a
join (select distinct id from another_table) b on b.id = a.id
where b.id = 1