注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 负载均衡技术沙龙问答汇集
 帮助

SQL查询中的连接


2007-08-08 13:17:18
 标签:SQL 查询   [推送到技术圈]

以下是SQL中的常用连接查询的简单写法,采用SQL-Server示例数据库pubs和Northwind
以下是详细代码:

use pubs
--内连接
select titleauthor.au_id,au_lname,title_id from authors inner join
titleauthor on titleauthor.au_id=authors.au_id
--内连接 (另一种写法,和上例结果一样)
select titleauthor.au_id,au_lname,title_id from authors ,
titleauthor where titleauthor.au_id=authors.au_id
--左外连接,将取出左表中的所有记录,右表没有对应将以Null进行添充
select titleauthor.au_id,au_lname,title_id from authors left join
titleauthor on titleauthor.au_id=authors.au_id

--右外连接,将取出右表中的所有记录,左表没有对应将以Null进行添充
select titleauthor.au_id,au_lname,title_id from authors right join
titleauthor on titleauthor.au_id=authors.au_id

--自连接,就是自己连接自己,
--如下题:请选择员工编号,员工姓名,及员工直接上级的编号,姓名
--解决方法:因为员工上级也是公司的员工,也在本表出现,这就要采用连接,而数据出自同一张表
--故采用自连接,自连接主要是给一张表起两个别名,假想成两张表来做,一切OK,
--代码如下:
use northwind

select a.employeeid,a.lastname,a.reportsto,b.lastname from employees a
 left join employees b on a.reportsto=b.employeeid
select employeeid,lastname,reportsto from employees




    文章评论
 
2007-08-09 14:40:38
多好的文章啊!!1

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: