实验三 连接查询(new).doc
文本预览下载声明
实验三 连接查询
一、实验目的及要求
1. 理解连接查询的作用。
2.理解等值连接与自然连接的不同之外。
3.掌握自连接的概念。
二、实验内容
示例1:在FROM子句中定义连接,返回一组产品(表Products中的记录)和供应商(表Suppliers中的记录)信息,在WHERE子句中限定单价高于10,且公司名以F开头。
USE Northwind
SELECT ProductID,Suppliers.SupplierID, CompanyName
FROM Suppliers JOIN Products
ON (Suppliers.SupplierID=Products.SupplierID)
WHERE UnitPrice$10 AND CompanyName like ‘F%’
示例2:在WHERE子句中定义连接
SELECT P.ProductID , S.SupplierID , S.CompanyName
FROM Suppliers AS S , Products AS P
WHERE S.SupplierID=P.SupplierID
AND P.UnitPrice$10
AND S.CompanyName like ‘F%’
该示例结果与上例相同。
示例3:等值连接
USE pubs
GO
SELECT *
FROM authors ,publishers
Where authors.city=publishers.city
ORDER BY authors.au_lname
该示例返回两个表中连接列的列值相等的所有列,其中返回列中包括两个city列,两个state列,均为重复列。
示例4:不等值连接
USE pubs
GO
SELECT publishers.pub_name,publishers.state,
authors.au_lname,authors.au_fname, authors.state
FROM publishers,authors
Where authors.statepublishers.state
And publishers.pub_name LIKE ‘a%’
ORDER BY authors.au_lname
该示例为一个大于()连接,用于查找洲名按字母顺序排列在CA之后下面的以A开头的出版社。结果如图所示。
示例5:自然连接
自然连接指定了需要返回的列,删除了重复列。
USE pubs
GO
SELECT publishers.pub_id, publishers.pub_name, authors.*
FROM authors INNER JOIN publishers
ON authors.city=publishers.city
ORDER BY authors.au_lname
注意和等值连接的区别
示例6:自连接
自连接就是使用一个表中的列进行比较连接,从而将该表中的行同另一些行连起来。
USE pubs
SELECT first.au_fname,first.au_lname,second. au_fname,second.au_lname
FROM authors first INNER JOIN authors second
ON first.zip=second.zip
WHERE first.city=’Oakland’
ORDER BY first.au_fname,first.au_lname
该示例使用了自连接,查询了city列值为Oakland的具有相同邮政编码的作者的姓名,
示例7:多表连接
多表连接就是将两个以上的表进行比较连接。要连接多个表只要在FROM子句中包含多个连接条件,多个连接条件可以用逻辑运算符AND或OR连接。
USE pubs
SELECT authors.au_fname,authors.au_lname, titles.title
FROM authors JOIN titleauthor
ON authors.au_id=titleauthor.au_id JOIN titles
ON titleauthor.title_id=titles.title_id
ORDER BY au_fname
该示例中建立了两个连接,从而连接了三个表:表authors、表titleauthors和表titles。在结果中没有表titleauthors的任何列,但是如果没有titleauthors这样的中间表,此连接无法实现。
三、思考题
1. 将上面所有用JOIN语句实现连接的例题改成通过WHERE子句实现内连接操作。
2.在示例6中,包含了重复数据。如果要删除结果中作者自身匹配的行以及完全相同
显示全部