码迷,mamicode.com
首页 > 数据库 > 详细

MySQL-SQL基础-子查询

时间:2019-01-11 11:25:54      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:HERE   birt   div   style   class   limit   weight   rgba   set   

#子查询-某些情况下,当进行查询的时候,需要的条件是另外一个select语句的结果,这个时候就要用到子查询。用于子查询的关键字主要包括:
in、not in、=、!=、exists、not exists等等。
#从emp表中查询出所有部门在dept表中的所有记录

mysql> select * from dept; +--------+----------+ | deptno | deptname | +--------+----------+ | 1 | tech | | 2 | sale | | 3 | hr | | 4 | sl | +--------+----------+ 4 rows in set (0.01 sec) mysql> select * from emp; +-------+------------+------------+---------+--------+------+ | ename | birth | hirdate | sal | deptno | age1 | +-------+------------+------------+---------+--------+------+ | zzx1 | 2000-01-01 | 2000-01-01 | 2000.00 | 1 | 21 | | zzx1 | 2002-03-09 | 2009-04-03 | 2001.00 | 3 | 22 | | ttx2 | 2023-04-10 | 2010-03-04 | 4000.00 | 4 | 23 | | ssss | 2019-01-01 | 2018-01-01 | 5000.00 | 2 | 24 | +-------+------------+------------+---------+--------+------+ 4 rows in set (0.00 sec) mysql> select * from emp where deptno in(select deptno from dept); +-------+------------+------------+---------+--------+------+ | ename | birth | hirdate | sal | deptno | age1 | +-------+------------+------------+---------+--------+------+ | zzx1 | 2000-01-01 | 2000-01-01 | 2000.00 | 1 | 21 | | ssss | 2019-01-01 | 2018-01-01 | 5000.00 | 2 | 24 | | zzx1 | 2002-03-09 | 2009-04-03 | 2001.00 | 3 | 22 | | ttx2 | 2023-04-10 | 2010-03-04 | 4000.00 | 4 | 23 | +-------+------------+------------+---------+--------+------+ 4 rows in set (0.00 sec)

 

#如果子查询记录数唯一,还可以用=代替in

mysql> select * from emp where deptno=(select deptno from dept limit 1);

+-------+------------+------------+---------+--------+------+

| ename | birth      | hirdate    | sal     | deptno | age1 |

+-------+------------+------------+---------+--------+------+

| zzx1  | 2000-01-01 | 2000-01-01 | 2000.00 |      1 |   21 |

+-------+------------+------------+---------+--------+------+

1 row in set (0.00 sec)

 

MySQL-SQL基础-子查询

标签:HERE   birt   div   style   class   limit   weight   rgba   set   

原文地址:https://www.cnblogs.com/drizzle-xu/p/10253847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!