Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

联合查询

Posted on 2008-08-12 15:54 Prayer 阅读(223) 评论(0)  编辑 收藏 引用 所属分类: 数据库,SQL
**********************************************************************************
联合查询
**********************************************************************************
查询表中的各个字段的值
select Sno,Sname,Ssex,Sdept from Student;

多表查询(2个表,publishtable和publishtable,给表起了别名)
select u.userid,u.age,u.username,p.publishname from usertable u,publishtable p where u.userid = p.publishid;

多表查询(3个表employees,departments和locations表,给表起别名)
(从多表中查询出所有姓smith的雇员的名字,所在部门以及部门所在的城市)
select e.first_name,e.last_name,d.department_name,l.city from employees e,departments d,locations l where e.department_id = d.department_id and d.location_id = l.location_id and e.last_name = 'smith';


***********************************************************************************
联合查询
***********************************************************************************

等值连接
/*将books表和表bookstype中的信息联合查询,条件是联系键相等*/
select * from books,bookstype where bookstype.typeid = books.typeid



内连接
/*将books表和表bookstype中的信息联合查询,条件是联系键相等,和等值连接等价*/
select * from books inner join bookstype on books.typeid = bookstype.typeid

左外连接

/*将books表和表bookstype中的信息联合查询,包括在books表中没有和bookstype表关联的信息*/
select * from books left outer join bookstype on bookstype.typeid = books.typeid

右外连接

/*将bookstype表和books表中的信息联合查询,包括在bookstype表中没有和books表关联的信息*/
select * from books right outer join bookstype on bookstype.typeid = books.typeid

全连接

/*将bookstype表和books表中的信息联合查询,包括在books表中没有和bookstype表关联的信息以及在bookstype表中没有和books表关联的信息*/

select * from books full outer join bookstype on bookstype.typeid = books.typeid


***********************************************************************************
联合查询
***********************************************************************************
多表查询应该注意的几点:
多表查询和单表查询的不同在于多表查询在查询某个字段的时候应该带上表名
格式是:表名.字段名,表名.字段名
select bbs.id,bbs.name,bbs.dep,bbsr.id,bbsr.name
from bbs,bbsr
where bbs.id=bbsr.id;
一般的在多表查询中的表名取的麻烦用别名来代替
如下:
select b.id,b.name,b.dep,c.id,c.name
from bbs as b ,bbsr as c // from bbs b,bbsr c***注意取别名也可以用空格或则用as.
where b.id=c.id;

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理