(第十章)多表查询之in,exitst

2021/5/4 10:57:53

本文主要是介绍(第十章)多表查询之in,exitst,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

子查询

子查询(嵌套查询),是嵌套在外层查询where子句中的查询

子查询为主查询返回其所需要的数据,或者对外查询的结果作进一步的限制

in子查询,在内层查询中返回某列的值,外层使用同样的列和子查询的返回值比较。
使用关键词in时,返回值可以有多个(使用关系运算符时,返回值只能是一个)。

exists用来检查子查询是否有查询结果返回,
返回的exists为ture 则外查询语句进行查询,
返回的exists为false ,外查询则不查询。exists返回的是一个布尔值
in语法:

select table1.col_name_n(多个字段) from table1 where col_name1 in [或not in] (select col_name1 from table2 where condition);

exists语法:

select table1.col_name_n from table1 where exists (select col_name1 from table2 where condition);

表e中记录了女性的个人信息,表t中记录了对应的附加信息,目的是:查询女性的所有附加信息
实例使用in :

select table_t.* from table_t where r1 in (select r1 from table_e where r2=“女”);
选择表t的所有字段为显示结果,主查询条件为:表t中的r1字段在(子查询条件为:表e中 r2=女的值的数据))

实例使用exists:

select table_t.* from table_t where exists (select r1 from table_e where r2=“女”);
从表t中显示表t的所有字段数据,exists为ture则显示,并在后面的数据中筛选,false则不显示,真假判断条件为(子查询,有数据则为ture,没有则为false)

主查询决定是否显示数据,不需要在主查询中匹配字段

2实例使用exists:

判断table_e中字段r1==table_t中r1中字段
select * from table_t A where exists (select r1 from table_e where table_e.r1=A.r1);
select * from table_t A where not exists (select r1 from table_e where table_e.r1=A.r1);
实例数据里面是table_t的数据比 table_e中的多
选择显示“妖艳”的女的信息:可以使用in和exists
select table_e.* from table_e where
r1 in
(select r1 from table_t where r2=“妖艳”);
select table_e.* from table_e where
exists
(select r1 from table_t where r2="妖艳"
and table_e.r1=table_t.r1 );

not exists
实例数据:
create table table_e(
r1 varchar(10),
r2 varchar(10),
r3 int,
r4 varchar(10)
);
insert into table_e values
(“a1”,“女”,1,“岁”),
(“a2”,“女”,2,“岁”),
(“a3”,“女”,8,“岁”),
(“a4”,“男”,4,“岁”),
(“a5”,“男”,5,“岁”),
(“a6”,“男”,6,“岁”),
(“a7”,“男”,7,“岁”);

create table table_t(
r1 varchar(10),
r2 varchar(10)
);

insert into table_t values
(“a1”,“丰满”),
(“a2”,“好身材”),
(“a3”,“妖艳”),
(“a4”,“有钱”),
(“a5”,“财大”),
(“a6”,“富有”);

注意: (a7不插入)



这篇关于(第十章)多表查询之in,exitst的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程