3

私は単純なSQLクエリを実行しようとしています:

SELECT DISTINCT id
FROM marketing
WHERE type = 'email'
  AND id NOT IN (
                SELECT id
                FROM marketing
                WHERE type = 'letter'
                )
ORDER BY id;

実行に非常に時間がかかり、whereステートメントのselectに関係していると思います(idが多数あります)が、改善する方法が思いつきません。

まず、これがクエリが非常に遅い理由であり、次にそれを改善する方法に関する提案はありますか?

編集:

データベース システム: MySql

Id は索引付けされていますが、このテーブルの主キーではありません。それは外部キーです。

4

4 に答える 4

2
select distinct id
from   marketing a
where  type = 'email'
and    not exists (
           select 'X'
           from   marketing b
           where  a.id = b.id
           and    type = 'letter' )
order by id
于 2013-05-09T20:11:23.153 に答える
1

このクエリを集計クエリとして表現することもできます。探している条件はid、 に少なくとも 1 つの行 where がtype = 'email'あり、行 where がないことtype = 'letter'です。

select id
from marketing m
group by id
having SUM(case when type = 'letter' then 1 else 0 end) = 0 and
       SUM(case when type = 'email' then 1 else 0 end) > 0

のインデックスを使用すると、このクエリの実行速度が向上する可能性がありますmarketing(id, type)。は順序付けを行うorder by idため、MySQL では冗長です。group by

于 2013-05-09T20:13:56.210 に答える