この記事では、SQL Server(Transact-SQL)の非相関サブクエリと相関サブクエリについて例
相関サブクエリ
相関サブクエリは、値が外部クエリに依存するサブクエリです。 相関サブクエリは、サブクエリによって選択された行ごとに一度、繰り返し実行されます。
相関サブクエリでは、サブクエリは一度実行され、結果の値を外部クエリのWHERE句に置き換えます。
注:外部クエリとは独立して相関サブクエリを実行することはできません。SQL Server(T-SQL)で相関サブクエリを理解するための2つのテーブルを作成しましょう。
製品テーブル:
MySQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
19
19
19
19
19
19
19
11
テーブルproductstableを作成します
(
id int主キー、
名前nvarchar(50)、
価格int、
詳細nvarchar(150)
)
Productstable値に挿入(1、’ラップトップ’、30000、’ホームユーザーのためのラップトップ’)
Productstable値に挿入(2、’洗濯機’、20000、’白い色のフロントロードマシン’)
ProductsTable値に挿入(3、’TV’、22000、’32イ/Div>
販売レコードテーブル:
MySQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
19
19
19
19
19
19
19
11
12
13
(
id int主キー id,
productid int,
soldquantity int,
(
id int主キー id,
productid int,
soldquantity int,
SaleDate Date
)
Insert into SaleRecordTable Values (2, 3, ’10-10-2016′)
Insert into SaleRecordTable Values (3, 5, ’10-10-2016′)
Insert into SaleRecordTable Values (2, 2, ’11-10-2016′)
Insert into SaleRecordTable Values (4, 6, ’11-10-2016′)
Insert into SaleRecordTable Values (2, 6, ’12-10-2016′)
Insert into SaleRecordTable Values (4, 6, ’13-10-2016′)
では、クエリは販売レコードテーブルから販売された製品の合計を取得します。 サブクエリでは、製品テーブルの製品idごとに合計製品販売データが取得されます。
MySQL
1
2
3
4
|
–correlated subquery
Select Name,
(Select SUM(SoldQuantity) from SaleRecordTable where ProductId = ProductsTable.ID)As’Total Quantity Sold’
from ProductsTable
|
Output:
サブクエリを独立して実行する場合は、次のようにします次のエラーが表示されます。
非相関サブクエリ
非相関サブクエリは、外部クエリとは独立したサブクエリです。 非相関サブクエリは、外部クエリとは独立して実行できます。
MySQL
1
2
3
4
|
–Non correlated query
Select ID, Name, Details
From ProductsTable
Where ID = (Select ProductID from SaleRecordTable Where SaleDate =’10-10-2016′ AND ProductID =2)
|
出力:
サブクエリを独立して実行する場合、今回はエラーは発生しません。 出力は次のようになります。
この記事がsql Serverの相関サブクエリと非相関サブクエリを理解するのに役立 クエリやフィードバックのためのあなたのコメントを投稿してください。 読んでくれてありがとう

The following two tabs change content below.






Unity3Dでのイベントの使用-2020年5月2日
- Bio
- Latest Posts



Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.





