exists/not exists的使用方法:
exists单词是存在的意思,not exists当然是不存在的意思了
exists使用方法一:
在执行createhe或者drop语句前,可以使用exists语句来判断该数据库对象是否存在,返回值是true和false。
例:
create database if not exists abs;
当数据库abs不存在时返回true,执行create
abc数据库存在时 返回false,create不执行。
drop database if exists abs;
abc数据库存在时 返回true,create执行。
数据库abs不存在时返回false,执行create。
使用exists创建表的原理同上。
exists使用方法二:
exists可以作为where语句的子查询,
例:
查询没有借阅信息的读者编号和读者姓名(reader:读者信息表,borrow :图书借阅表)
select rid '读者编号',rname '读者姓名' from reader r where not exists(select nif from borrow where r.rid=borrow.rid);
上面查询语句返回结果为
若该子查询没有返回值则为turn,然后执行外层查询语句,若子查询有返回值,则为false,此时外层语句不在执行查询。
例:
查询有借阅信息的读者编号和读者姓名(reader:读者信息表,borrow :图书借阅表)
select rid '读者编号',rname '读者姓名' from reader r where exists(select nif from borrow where r.rid=borrow.rid);
若该子查询有返回值则为turn,然后执行外层查询语句,若子查询没有返回值,则为false,此时外层语句不在执行查询。