サブクエリ
-
概要
- はじめに: SQL ステートメント内のネストされた選択ステートメントは、ネストされたクエリと呼ばれ、サブクエリとも呼ばれます。
- 形式:select * from t1 where column1 = (select column1 from t2....)
- サブクエリの外部ステートメントは、insert/update/delete/select のいずれかになります。最も一般的なのは select です。
-
分類
-
スカラーサブクエリ
- サブクエリによって返される結果は、最も単純な形式の単一の値 (数値、文字列、日付など) です。
- 一般的な記号: =、<>、>、>=、<、<=
- 具体的なデモコードは以下の通りです
-
-- todo 子查询 -- 标量子查询 -- A.查询“教研部”的所有员工信息 -- a.查询 教研部 的部门id select tb_dept.id from tb_dept where name = '教研部'; -- b.再查询该部门id下的员工信息 select * from tb_emp where dept_id = 2; -- 最终语句如下 select * from tb_emp where dept_id = (select id from tb_dept where name = '教研部'); -- select id from tb_dept where name = '教研部' 该语句属于子查询 -- B.查询在“东方白”入职后的员工信息 -- a.查询’东方白‘的入职时间 select entrydate from tb_emp where name = '方东白'; -- b.查询在方东白入职之后的员工信息 select * from tb_emp where entrydate > '2012-11-01'; -- 最终语句如下 select * from tb_emp where entrydate > (select entrydate from tb_emp where name = '方东白') -- 子查询的语句 # select entrydate # from tb_emp # where name = '方东白'
-
- サブクエリによって返される結果は、最も単純な形式の単一の値 (数値、文字列、日付など) です。
-
列クエリ
-
サブクエリによって返される結果は列 (複数行の場合もあります) です。
-
- よく使用される記号: in、not in など。
- 具体的なデモコードは以下の通りです
-
-- todo 列子查询 -- A.查询’教研部‘和’咨询部‘员工的所有信息 -- a.获取两部门的部门id select id from tb_dept where name = '教研部' or name = '咨询部'; -- b.根据部门id,查询该部门下的员工id select * from tb_emp where dept_id in (2, 3); -- 合并后的查询语句 select * from tb_emp where dept_id in (select id from tb_dept where name = '教研部' or name = '咨询部');
-
-
-
行サブクエリ
-
サブクエリによって返される結果は 1 行です (複数列の場合もあります)。
-
具体的なデモコードは以下の通りです
-
-- todo 行查询 -- A.查询与‘韦一笑’的入职日期及职位都相同的员工信息 -- a.查询‘韦一笑’ 的入职日期 及 职位 select entrydate, job from tb_emp where name = '韦一笑'; -- b.查询与‘韦一笑’的入职日期及职位相同的员工信息 select * from tb_emp where entrydate = '2007-01-01' and job = 2; select * from tb_emp where (entrydate, job) = ('2007-01-01', 2); -- 合并查询语句 select * from tb_emp where (entrydate, job) = (select entrydate, job from tb_emp where name = '韦一笑');
-
-
-
テーブルサブクエリ
-
サブクエリによって返される結果は複数行および複数列であり、一時テーブルとしてよく使用されます。
-
よく使用される演算子: in
-
特定のオペレーションコード
-
-- todo 表子查询 -- A.查询入职日期是’2006-01-01‘之后的员工信息,及部门名称 -- a.查询入职日期为’2006-01-01‘之后的员工信息 select * from tb_emp where entrydate > '2006-01-01'; -- b.查询这部分员工信息及其部门名称 select * from (select * from tb_emp where entrydate > '2006-01-01') e, tb_dept d where e.dept_id = d.id; # select * # from tb_emp # where entrydate > '2006-01-01' 为子查询
-
-
-