サブクエリはネストされたクエリとも呼ばれ、メモリと熟練した使用を容易にするために、サブクエリのさまざまな操作と処理を要約します。
コンセプト:サブクエリとは何ですか?
サブクエリは、クエリステートメントを別のクエリステートメントにネストすることです。内側のステートメントのクエリ結果は、外側のクエリステートメントの条件として使用できます。この記事では、whereまたはhaingキーワードの後の状況に焦点を当てます。もちろん、Limitedだけではありません。この状況に。
サブクエリは、次の3つの状況に分けられます(ここでは、使用頻度の高い3つの状況のみを要約します)。
1.列サブクエリ(複数行サブクエリ、つまり、サブクエリの結果セットは複数行と単一列)。位置はwhereとhasの後に配置されます。
次の一般的な状況が含まれています。
1.サブクエリで[not]を使用します
2.比較演算子を使用したサブクエリ(=、>、> =、<=、<>、!=、<=>)
3. [not]を使用したサブクエリが存在します
4.右の図に示すように、一部またはすべてのサブクエリを使用します。
フロート操作 | 意味 |
IN / NOT IN | リスト内のいずれかに等しい |
いずれか|一部 | サブクエリによって返される値と比較する |
すべて | サブクエリによって返されるすべての値と比較します |
演算子|キーワード | どれか | いくつか | すべて |
>> = | 最小 | 最小 | マックス |
<< = | マックス | マックス | 最小 |
= | 任意の値 | 任意の値 | |
<>!= | 任意の値 |
(仅示例)
select id ,username from student where score >=any(select level from scholarship);大于等于任意一个,即取最小值
select id ,username from student where score >=some(select level from scholarship)同上
select id ,username from student where score >=all(select level from scholarship)大于等于所有的,就是大于等于里面最大的那个
其他情况参考这个示例
2つのスカラー量子クエリ
スカラーサブクエリのサブ結果セットは単一の行と単一の列であり、サブクエリの条件は通常、whereまたはhaveの後に配置され、「;」を追加せずに()に配置する必要があります。
説明する:
select * from employees
where salary >(
select salary from employees where
last_name='Abel'
);
select department_id ,min(salary) from employees
group by department_id
having min(salary) >(
select min(salay)
from employees where department_id =50
);
3行のサブクエリ(結果セットは1行と複数の列、または複数の行と複数の列であり、使用量が少ないため、推奨されません)
例えば:
select * from employees
where (employee_id ,salary )=(
select min(employee_id),max(salary)
from employees
);
当然用之前的方法也是可以解决的:
select * from empioyees
where employee_id=(
select min(employee_id) from employees
)
and
salary=(
select max(salary) from employees
);
もちろん、テーブルを作成するときのサブクエリには、次のような他の用途もあります。
クエリ結果をデータテーブルに書き込む
テーブルの挿入[column_name、.......]テーブルからcolumn_name、.......を選択します。
データテーブルの作成中にクエリ結果をデータテーブルに書き込みます
存在しない場合はテーブルを作成しますtable_name [create_definition、......] select_statement
ps:ここで、新しく作成されたテーブルのフィールドは、対応するフィールドに従ってデータを生成する前に、クエリフィールドと一致している必要があることに注意してください。一貫性がない場合、新しいフィールドは元のベースで生成されます。
create table test2 (id tinyint unsigned auto_increment key ,num tinyint unsigned ) select id ,level from scholarship ;
+------+----+-------+
| num | id | level |
+------+----+-------+
| NULL | 1 | 90 |
| NULL | 2 | 80 |
| NULL | 3 | 70 |
+------+----+-------+
这样就多出了一个level字段或者说num字段没有用上,如果我们把num字段改成level就能生成合适的表格内容了。
+----+-------+
| id | level |
+----+-------+
| 1 | 90 |
| 2 | 80 |
| 3 | 70 |
+----+-------+
さらに、いくつかのサブクエリステートメントがselectの下に配置されます。例を挙げて説明します。
select d.*,(
select count(*)
from employees e
where e.department=d.department
)
from departments d;
select (
select department_name from departments d
join employees e
on d.department_id =e.department_id
) from departments d;
別の部分はfromの後に配置されます。通常、fromの後にテーブルが続きます。これは、サブクエリの結果セットをテーブルとして扱うことと同じです。これ以上の例はありません。興味がある場合は、Baiduを使用できます。