ylbtech-SQL Server:SQL Server-子查询(嵌套子查询)和子查询(相关子查询) |
SQL Server 子查询(嵌套子查询)和子查询(相关子查询)。
-- =============================================
-- ylb:本案例的目的是:“嵌套子查询”
-- 11:25 2011/12/9
-- =============================================
use pubs
go
--一、子查询
--1,嵌套子查询
---特点:in里面的查询语句可以独立运行。
--P1:查询图书名是“Net Etiquette”的作者是谁?
--分析
select title_id from titles where title='Net Etiquette'
--title_id='PC9999'
go
select au_id from titleauthor
where title_id='PC9999'
--au_id='486-29-1786'
go
--小结
select au_id from titleauthor
where title_id in(select title_id from titles where title='Net Etiquette')
go
select * from authors
where au_id='486-29-1786'
--总结
select * from authors
where au_id in(select au_id from titleauthor
where title_id in(select title_id from titles where title='Net Etiquette'))
--测试1,
--P2:查看图书编号是‘PC9999’的出版社名称是?
select pub_id from titles
where title_id='PC9999'
go
select pub_name from publishers
where pub_id=''
go
--结论
select pub_name from publishers
where pub_id in(select pub_id from titles
where title_id='PC9999')
go
-- =============================================
-- ylb:本案例探讨的是:“相关子查询”
-- 11:25 2011/12/9
-- =============================================
use pubs
go
--一、相关子查询
--P1:查询出版社和商店在同一个州的商店名称?
go
select * from publishers
select * from stores
go
--结论
select stor_name from stores s
where state in(select state from publishers where state=s.state)
go
--P2:查询出版社和作者在同一个的作者姓名?
select * from publishers
select * from authors
go
--结论
select * from authors a
where state in (select state from publishers where state=a.state)