一尘不染

创建存储过程并编写查询以基于 SQL Server 中的列连接多表

sql

我是 SQL 的初学者,这是我在 SQL 中创建存储过程的第一个练习。我需要获取所有具有列FirstNameMiddleNameLastNameemail address和的人的所有phone numberphonenumber type

我必须加入(需要使用加入)这 4 个表、、、Person.personperson.personphone检索上面提到的列person.phonenumbertypeperson.emailaddress

我使用的数据是 AdventureWorks 2016 SQL Server 示例数据库,它有大约 20k 行。

我尝试在两个表上进行内部连接,但执行似乎永无止境。

select FirstName as firstname 
from Person.Person
inner join person.EmailAddress on Person.Person.BusinessEntityID = Person.EmailAddress.BusinessEntityID 

阅读 89

收藏
2022-07-21

共1个答案

一尘不染

你需要这样的东西:

-- 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 条件更具可读性!

2022-07-21