1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MySQL IN句を用いて楽に絞り込みを行おう

Last updated at Posted at 2022-01-27

概要

  • MySQLのwhere句とin句を用いて同じカラムの複数条件絞り込みを楽に行う方法をまとめる

in句を使わないと??

  • fooテーブルのidが 1, 5, 11, 15, 198の情報を表示したい場合通常下記のようなSQL句になる。

    select * from foo
    where id = 1
    or id = 5
    or id = 11
    or id = 15
    or id = 198;
    
  • これでも一切問題は無いがorをたくさん記載しないと行けない。

  • 改行したらしたで複数行に渡って記載しないといけないし、改行しないとなんとなく分かりにくいし。

in句を使ってみよう

  • 先程と同じ条件のSQLをin句を用いて記載してみると下記の様に記載する事ができる。

    select * from foo
    where id in (1, 5, 11, 15, 198);
    
  • in句の後にカッコ書きで絞り込みたい数値を記載すれば良い。

  • 上記はidによる絞り込み。文字列で絞り込みをしたい場合は絞り込み用の値を"でくくってあげればいい。

    select * from foo
    where str in ("文字列A", "文字列B", "文字列C");
    
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?