0
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 3 years have passed since last update.

EXISTSの使用方法

Posted at

「EXISTS」とは

「EXISTS」は、「サブクエリ」を扱う仕組み。SELECT文で取得したものを、SELECTやUPDATE処理で使用することを指す。


/*! 構文 */

SELECT [表示要素名] FROM [テーブル名]
  WHERE EXISTS (
    [入れ子にするSELECT]
  );

サンプル


SELECT * FROM company WHERE EXISTS (
    SELECT * FROM company_sub
      WHERE company.id = company_sub.id AND user_sub.name = "A社"
  );

###テーブル同士のひも付き


WHERE company.id = company_sub.id AND company_sub.job = "A社"

「company.id = company_sub.id」部分で、テーブル同士のひも付けを指定し、これによってcompanyテーブル側と、company_subテーブル側で連携が取れており、この記述がないと以下のように全部が表示されてしまう。

SELECT * FROM company WHERE EXISTS (
    SELECT * FROM company_sub
      WHERE company_sub.job = "A社"
  );

テーブル同士のひも付きの漏れがないか注意が必要。

参考文献

0
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
0
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?