サブクエリの返答は単一行のみ!もしくは述語の指定が必要!

複数行を返すとエラーになります

Where句で使用するサブクエリの問い合わせ結果が2行以上になってしまうと「single-row subquery returns more than one row」のエラーが帰ってきます。

SQL> select * from test
 where no = (select no from test); 
 where no = (select no from test)
             *
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row

サブクエリの結果が複数帰ってきてしまうとNo列の比較にどの値を使用したら良いのか分からない為のエラーです。

そのため、サブクエリの帰ってくる値を単一にする必要があります。

サブクエリを使用する時はケースバイケースのため、その都度サブクエリの帰ってくる件数を意識しましょう。

SQL>  select * from test
 where no = (select no from test where no = 1);  

	NO NAME
---------- --------------------------------------------------
	 1 aaaaa
SQL> select * from test
  where no = (select max(no) from test);    

	NO NAME
---------- --------------------------------------------------
	 5 youo

サブクエリの結果を複数行受け取れる述語

もしサブクエリの帰ってくる件数を複数のときにしたい場合は「IN」や「EXISTS」、「ANY」などの述語を指定します。

これらの述語を使用することでサブクエリの結果のどれかと一致するものを正とする事を表現することが出来ます。

SQL> select * from test
 where no IN(select no from test0);   

	NO NAME
---------- --------------------------------------------------
	 1 aaaaa
	 2 iiiii
	 2 uouoo

 

SQL> select * from test
 where exists(select no from test0 where test.no = test0.no);  2  

	NO NAME
---------- --------------------------------------------------
	 1 aaaaa
	 2 iiiii
	 2 uouoo

 

SQL> select * from test
 where no = ANY(select no from test0);  2  

	NO NAME
---------- --------------------------------------------------
	 1 aaaaa
	 2 iiiii
	 2 uouoo

 

 

Twitterでフォローしよう

読んでみーな
おすすめの記事