我是 SQL 的初学者,这是我在 SQL 中创建存储过程的第一个练习。我需要获取所有具有列FirstName、MiddleName、LastName、email address和的人的所有phone number行phonenumber type。
FirstName
MiddleName
LastName
email address
phone number
phonenumber type
我必须加入(需要使用加入)这 4 个表、、、Person.person和person.personphone检索上面提到的列person.phonenumbertype。person.emailaddress
Person.person
person.personphone
person.phonenumbertype
person.emailaddress
我使用的数据是 AdventureWorks 2016 SQL Server 示例数据库,它有大约 20k 行。
我尝试在两个表上进行内部连接,但执行似乎永无止境。
select FirstName as firstname from Person.Person inner join person.EmailAddress on Person.Person.BusinessEntityID = Person.EmailAddress.BusinessEntityID
你需要这样的东西:
-- select the columns you want SELECT p.FirstName, p.MiddleName, p.LastName, pe.EmailAddress, pp.PhoneNumber, pnt.Name AS PhoneNumberType FROM -- this is your "base" table - where most of the info exists Person.Person p INNER JOIN -- join to the e-mail table - based on "BusinessEntityID", to get e-mail address Person.EmailAddress pe ON pe.BusinessEntityID = p.BusinessEntityID INNER JOIN -- join to the person phone table - based again on "BusinessEntityID", to get phone number Person.PersonPhone pp ON pp.BusinessEntityID = p.BusinessEntityID INNER JOIN -- join the PersonPhone table to the PhoneNumberType table, to get the type of phone Person.PhoneNumberType pnt ON pnt.PhoneNumberTypeID = pp.PhoneNumberTypeID
您应该始终为您的表使用正确/有意义的别名 - 这使得您的列列表被选中,并且您的 JOIN 条件更具可读性!