以下是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 |
转载于:https://blog.51cto.com/daimi5566/37466