您的位置:首页 > 其它

多表查询——where中一张字段不为null,并且不在另外一张表中被指向(不被外键指了)

2012-09-14 11:23 239 查看
我想要知道父表中的记录,有没有被子表中的外键指向。

父表建表语句:

CREATE TABLE tb_super_specialist(super_id integer primary key, super_name varchar(10), super_hospital integer, super_infor TEXT,  foreign key(super_hospital) references tb_hospital(hospital_id) on delete cascade )


子表建表语句:

CREATE TABLE tb_specialist(specialist_id integer primary key, specialist_name varchar(10), specialist_super integer, specialist_infor TEXT)


初始化父表:

insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(1,"内科",1,"我是内科的infor");
insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(2,"内科",1,"null");
insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(3,"外科",1,"我是外科");
insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(4,"外科",1,"我是外科");
insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(5,"内科",1,"我是内科的infor");
insert into tb_super_specialist(super_id,super_name,super_hospital,super_infor) values(6,"外科",1,"null");


初始化子表:

insert into tb_specialist(specialist_id,specialist_name,specialist_super,specialist_infor) values(1,"神经内科",3,"神经内科的infor");
insert into tb_specialist(specialist_id,specialist_name,specialist_super,specialist_infor) values(2,"神经内科",5,"神经内科的infor");
insert into tb_specialist(specialist_id,specialist_name,specialist_super,specialist_infor) values(3,"神经内科",2,"神经内科的infor");
insert into tb_specialist(specialist_id,specialist_name,specialist_super,specialist_infor) values(4,"神经内科",6,"神经内科的infor");


接下来,我想要知道,在父表中没有被子表外键关系的,且super_infor字段不为null的记录,查询语句:

select super_id,super_hospital,super_infor,super_name from tb_super_specialist
where super_infor != "null"  and super_id not in  (select distinct specialist_super from tb_specialist);!这才是重点


主要是not in关键字的使用

参考:http://www.w3school.com.cn/sql/sql_distinct.asp

参考:http://www.w3school.com.cn/sql/sql_in.asp

参考:http://www.iteao.com/html/webkaifa/Sql/1178819.html

In:等值连接,用来查找多表相同字段的记录

Not In:非等值连接,用来查找不存在的记录

Inner join:内连接,主要用来查找都符合条件的记录

Left join:左连接,主要用来查找左边有,右边没有的用空值表达

Right join:右连接,主要用来查找右边有,左边没有的用空值表达

Order By:升序 Asc 降序 Desc

Group By:分组排序 按字段分组(如按班级分),使用的都要有集合函数存在

Having:对分组条件进行判断,使用都要确保每个字段都要用集合函数

COMPUTE BY:子句使您得以用同一 SELECT 语句既查看明细行,又查看汇总行,可以计算子组的汇总值,也可以计算整个结果集的汇总值,行聚合函数名称;例如,SUM、AVG、MIN、MAX 或 COUNT
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: