我有一个必须从多个表中检索数据的存储过程
类似
SELECT [AppointmentId]
,[ContactId]
,[Date]
,[BookedBy]
,[Details]
,[Status]
,[Time]
,[Type]
,[JobId]
,[AppointmentFor]
,(Select PersonFirstName from Person where Person_Id = [AppointmentFor]) As UserFirstName
,(Select PersonLastName from Person where Person_Id = [AppointmentFor]) As UserLastName
,(Select PersonFirstName from Person where Person_Id = [ContactId]) As ContactFirstName
,(Select PersonLastName from Person where Person_Id = [ContactId]) As ContactLastName
FROM [dbo].[Appointments]
我的问题是 有没有其他更有效的方法来做到这一点?或者这是正确的方法吗?
我正在使用Sql server 2008 感谢
答案 0 :(得分:5)
如果我理解正确,你需要使用两个连接,这样你就可以在[AppointmentFor]和[ContactId]上匹配。
我也把桌子别名,这是一个很好的习惯,当你加入多个桌子时。
SELECT a.[AppointmentId]
,a.[ContactId]
,a.[Date]
,a.[BookedBy]
,a.[Details]
,a.[Status]
,a.[Time]
,a.[Type]
,a.[JobId]
,a.[AppointmentFor]
,p1.PersonFirstName As UserFirstName
,p1.PersonLastName As UserLastName
,p2.PersonFirstName As ContactFirstName
,p2.PersonLastName As ContactLastName
FROM [dbo].[Appointments] a
INNER JOIN Person p1 ON p1.Person_Id = a.[AppointmentFor]
INNER JOIN Person p2 ON p2.Person_Id = a.[ContactId]
答案 1 :(得分:0)
CREATE PROCEDURE up_getData
select personId,
name,
surname,
street address,
Postcode,
FROM Persons p
JOIN Address a on a.PersonId = p.personId
答案 2 :(得分:0)
是的,您应该使用联接:
SELECT a.[AppointmentId]
,a.[ContactId]
,a.[Date]
,a.[BookedBy]
,a.[Details]
,a.[Status]
,a.[Time]
,a.[Type]
,a.[JobId]
,a.[AppointmentFor]
,p.PersonFirstName
,p.PersonLastName
,p2.PersonFirstName
,p2.PersonLastName
FROM Appointments a
JOIN Person p ON a.AppointmentFor = p.Person_Id
JOIN Person p2 ON a.ContactId = p2.Person_Id
答案 3 :(得分:0)
SELECT [AppointmentId]
,[ContactId]
,[Date]
,[BookedBy]
,[Details]
,[Status]
,[Time]
,[Type]
,[JobId]
,[AppointmentFor]
,b.PersonFirstName UserFirstName
,b.PersonLasName UserLastName
,c.PersonFirstName ContactFirstName
,c.PersonLastName ContactLastName
FROM [dbo].[Appointments] a
JOIN Person b on a.ApointmentFor = b.Person_Id
JOIN Person c on a.ContactId = c.ContactId