首页 > 代码库 > SQL连接、合并、子查询
SQL连接、合并、子查询
连接:连接分为内连接、外连接、交叉连接
内连接和外连接都是在笛卡尔积的基础做一些修改。
合并查询:把两个相似的结果可以用union联合起来。
mysql> select id,time from exam -> union -> select id,time from recuit;+-----+------------+| id | time |+-----+------------+| 1 | 2016-08-30 || 2 | 2016-09-10 || 8 | NULL || 9 | 2016-08-31 || 100 | 2014-08-06 || 1 | 2016-08-31 || 2 | 2016-08-25 || 3 | 2016-08-31 |+-----+------------+8 rows in set (0.14 sec)
子查询:
当子查询为单行单列时:可以用子查询的某条记录作为where condition的元素之一。
mysql> select id from recuit -> where id> -> (select id from exam where name="tengxun");+----+| id |+----+| 2 || 3 || 9 |+----+3 rows in set (0.12 sec)mysql> (select id from exam where name="tengxun");+----+| id |+----+| 1 |+----+1 row in set (0.00 sec)
子查询的返回值为多行多列时:
mysql> select * from recuit -> where (id,time) -> > -> (select id,time from exam where id=1);+----+------------+-----------------+---------+--------+| id | time | process | name | result |+----+------------+-----------------+---------+--------+| 1 | 2016-08-31 | wait for result | baidu | 1 || 2 | 2016-08-25 | haha | tengxun | 1 || 3 | 2016-08-31 | jiayou | wangyi | 1 || 9 | 2016-08-31 | happy | wangyi | 1 |+----+------------+-----------------+---------+--------+4 rows in set (0.02 sec)
带有关键字In的查询,当主查询的条件是子查询的查询结果中时,就可以通过关键字in来判断。相反如果不是可以用not in。
select * from table_namewhere field_name in(select field_name from table_name);
带有关键字ANY的查询:
=ANY:功能与in一样。
>ANY: 返回比子查询中最小的还要大的记录。只要大于子查询中其中一个就行了。
<ANY:返回比子查询中最大的还要小的记录。只要小于一个就行了。
带有关键字ALL的查询:
>ALL:比最大的还要大。
<ALL:比最小的还要小。
带有关键字exists:
exist的子查询实际上不返回任何记录,而是返回true和false,如果子查询存在至少一条记录,就会返回true。否则就是false.
问题1: --users表有1000条记录,id自增,id都大于0select * from users where exists (select * from users limit 0); --输出多少条记录?select * from users where exists (select * from users where id < 0); --输出多少条记录?答案(请选中查看):10000条0条 原因:exists查询的本质,只要碰到有记录,则返回true;所以limit根本就不会去管,或者说执行不到。 问题2:exists可以完全代替in吗?不能。例如:--没有关联字段的情况:枚举常量select * from areas where id in (4, 5, 6);--没有关联字段的情况:这样exists对子查询,要么全true,要么全falseselect * from areas where id in (select city_id from deals where deals.name = ‘xxx‘);
SQL连接、合并、子查询
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。