4

私はこの猫のID - 投稿IDの関係テーブルを持っています。

+----+--------+---------+
| id | cat_id | post_id |
|    |        |         |
| 1  |   11   |   32    |
| 2  |   ...  |   ...   |
+----+--------+---------+

を使用SELECT WHERE cat_id = 11 AND post_id = 32し、結果が見つからない場合は使用しますINSERT。これら 2 つのクエリを 1 つに書き直すことはできますか?

4

3 に答える 3

4

次のようなことができます。

insert into cats_rel(cat_id, post_id)
    select 11, 32
    where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32);

編集:

おっとっと。from節がないため、上記は MySQL では機能しません(ただし、他の多くのデータベースでは機能します)。いずれにせよ、私は通常、サブクエリに値を入れてこれを書きます。したがって、それらはクエリに一度だけ表示されます。

insert into cats_rel(cat_id, post_id)
    select toinsert.cat_id, toinsert.post_id
    from (select 11 as cat_id, 32 as post_id) toinsert
    where not exists (select 1
                      from cats_rel cr
                      where cr.cat_id = toinsert.cat_id and cr.post_id = toinsert.post_id
                     );
于 2013-08-24T18:45:11.607 に答える
0

MySQL には「from dual」句を使用できます。

insert into cats_rel(cat_id, post_id)
select 11, 32 from dual
where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32);
于 2017-01-08T12:10:31.263 に答える