SQL查询中的连接
2007-04-21 18:55
344 查看
以下是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
以下是详细代码:
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
相关文章推荐
- SQL查询出字段进行连接
- C#连接SQL多条件复杂查询
- SQL各种连接查询详解
- SQL连接查询
- SQL连接查询2 外连接(左右联接查询)
- 【SQL】—多表查询的几种连接方式
- ASP.NET实现列表页连接查询 拼接sql语句 绑定grivdView
- 深入探索SQL连接查询
- SQL三表连接查询与集合的并、交、差运算查询
- SQL 数据库 学习 029 查询-12 连接查询 --- 内连接
- T-SQL查询高级--理解SQL SERVER中非聚集索引的覆盖,连接,交叉和过滤
- SQL各种连接查询详解(左连接、右连接..)
- Hibernate中关于多表连接查询hql 和 sql 返回值集合中对象问题
- Sql语句优化-查询两表不同行NOT IN、NOT EXISTS、连接查询Left Join
- MySQL——查询sql总结:简单查询、连接查询、子查询
- sql连接查询中,where关键字的位置
- SQL 学习笔记<三> SELECT之连接查询
- Oracle中SQL语句学习六((连接查询)
- Oracle_学习使用SQL语句六(连接查询)
- SQL学习笔记八 索引,表连接,子查询,ROW_NUMBER