tusbasaのブログ

業務や勉強中に調べたことを自分用にメモするブログ

【SQL】サブクエリを使う際の注意

サブクエリを使う際、サブクエリ によって取得するレコードが一つ以上ある場合注意が必要。 「=」,「<」,「>」を使っているとエラーが発生する。(このような戻り値が1行だけのサブクエリをスカラサブクエリ という。)INを使用するとエラーが起こらない。

サブクエリでもし複数のレコードが返るとエラーが発生する

select
  posts.content
from
  posts
where
  user_id = (select users.id from users where users.name = taro)



サブクエリでもし複数のレコードが返ってもエラーは発生しない

select
  posts.content
from
  posts
where
  user_id in (select users.id from users where users.name = taro)

<>br

参考 https://zukucode.com/2017/09/sql-subquery-select.html