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
相关文章
相关标签/搜索