sql查询之内连接、外连接、子查询、嵌套表查询

--内连接
select dictinfo.*,dicttype.*
from dictinfo,dicttype
where dictinfo.typecode = dicttype.typecode; --typecode就是外键


--查询系统用户类型名称,用内连接实现
--只要在关联表中可以查询出一条记录就可以使用内连接
--如果从关联表中查询得到多条记录有重复记录,使用内连接如果出现重复记录,则大部分情况说明你的查询是错误的,
--在确保sql查询没有逻辑错误的情况下可以使用distinct去除重复记录

--查询系统用户类型名称,用内连接实现
--系统用户类型代码和名称之间的关系
select * from dictinfo;
select dictcode,info,id from dictinfo where typecode='s01';

--第一种写法 :
select userid,groupid,info from sysuser,(select dictcode,info,id from dictinfo where typecode='s01') grouptable
where sysuser.groupid = grouptable.dictcode;
--第二种写法
select userid,groupid,info from sysuser,(select dictcode,info,id,typecode from dictinfo) grouptable
where sysuser.groupid = grouptable.dictcode and grouptable.typecode='s01';


--外连接

--需求:查询系统用户表中对应的医院单位名称(如果该用户是医院用户则显示医院名称)
--主查询表是系统用户表,关联查询表是医院单位表
--只有部分记录可以从关联查询表中查询到,主查询表要想显示所有记录,只能和关联查询表通过外连接进行查询
--显示全部数据的是主查询表,显示部分数据的是关联查询表

--left join 左外连接,left左边是主查询表;
--right join 右外连接,right右边是主查询表

select sysuser.*,useryy.mc from sysuser left join useryy on sysuser.sysid = useryy.id;

--上边的sql如果使用内连接,则会只查询出系统用户在医院单位中存在的记录,即两张表中都有的数据,这样查询到的数据就会少,如下
select sysuser.*,useryy.mc from sysuser,useryy where sysuser.sysid = useryy.id;

--使用右外连接完成
select sysuser.*,useryy.mc from useryy right join sysuser on sysuser.sysid = useryy.id;


--子查询
--需求:查询系统用户表,关联查询单位名称,关联查询用户类型的名称
--思路:一般是通过关联表的的主键进行关联查询的;也可以不通过关联表的的主键查询(注意,不使用联表的的主键进行查询时,子查询关联查询的结果只能有一条记录)
--结论:在主表上做子查询,主表的记录会全部显示
select sysuser.*,
(select mc from useryy where id = sysuser.sysid) useryymc,
(select info from dictinfo where dictinfo.dictcode = sysuser.groupid and dictinfo.typecode = 's01') --dictcode和typecode唯一确定一条记录
from sysuser;

--嵌套表查询
--嵌套表的层级是有限制的,不能无限嵌套下去
--将嵌套的结果当成一个表的时候,嵌套子查询中的列是不能重复的!!!

select * from(
select sy

suser.*,
(select mc from useryy where id = sysuser.sysid) useryymc,
(select info from dictinfo where dictinfo.dictcode = sysuser.groupid and dictinfo.typecode = 's01') --dictcode和typecode唯一确定一条记录
from sysuser
)

相关主题
相关文档
最新文档