我需要一些帮助...
我有2个内部sql服务器,一个包含学生信息,第二个包含库存。
我想要做的是将两者链接在一起并从“userfile”服务器获取额外的表。
下面是我从学生信息中提取的sql的一部分,我知道它有效。
fyi,sql的第一部分工作 - 我从SQL的第一部分得到了所有表,但没有得到第二部分 (和 PupilPersonalDetails.PupilID内连接[MYSERVERNAME] .USERFILE.dbo.pupil on PupilID = user_file_userid)
感谢您的帮助
includeNonActive
答案 0 :(得分:1)
请像这样写清楚
请测试以下
从[win2k12sql.USERFILE.dbo.pupil中选择*,其中pupilID = NumberYouKnowExists其中('%wc%' ='%wc%')
SELECT CurrentPupil.SchoolID as 'SchoolID', CurrentPupil.PupilID as
'PupilID', PupilPersonalDetails.Surname as 'Surname',
PupilPersonalDetails.Forename as 'First_Name',
PupilCurrentSchoolYearGroupLookupDetails.Description as 'Year_Group'
FROM CurrentPupil
LEFT OUTER JOIN PupilPersonalDetails AS PupilPersonalDetails ON
CurrentPupil.SchoolID = PupilPersonalDetails.SchoolID AND
CurrentPupil.PupilID = PupilPersonalDetails.PupilID
LEFT OUTER JOIN PupilCurrentSchool AS
PupilCurrentSchool ON CurrentPupil.SchoolID = PupilCurrentSchool.SchoolID
AND
CurrentPupil.PupilID = PupilCurrentSchool.PupilID
LEFT OUTER JOIN LookupDetails AS PupilCurrentSchoolYearGroupLookupDetails
ON
PupilCurrentSchoolYearGroupLookupDetails.LookupDetailsID =
PupilCurrentSchool.YearGroup
AND
PupilCurrentSchoolYearGroupLookupDetails.LookupID = '3004'
AND
PupilPersonalDetails.PupilID --do you have an issue here?
inner join [win2k12sql].USERFILE.dbo.pupil on
PupilID = user_file_userid
WHERE ('%wc%' = '%wc%')
答案 1 :(得分:1)
如果您使用了一些别名,那么您的查询将更容易使用。公平地说,您的代码中有很多别名,但别名与表名相同。这就像是说我的名字是“Sean Lange”,也被称为“Sean Lange”。我喜欢使用相当短的别名,然后尽可能保持它们在查询之间保持一致。
也不要使用字符串文字作为别名。它会工作,但它增加了混乱,更多的击键和零利益。除非您希望列的名称在结果集中不同,否则不需要列上的别名。
只需一些别名并格式化文本墙,查询就变得很容易看到发生了什么。所有整理你的查询可能看起来像这样。
SELECT
cp.SchoolID
, cp.PupilID
, ppd.Surname
, ppd.Forename AS First_Name
, pcsygld.Description AS Year_Group
FROM CurrentPupil cp
LEFT OUTER JOIN PupilPersonalDetails AS ppd ON cp.SchoolID = ppd.SchoolID
AND cp.PupilID = ppd.PupilID
LEFT OUTER JOIN PupilCurrentSchool AS pcs ON cp.SchoolID = pcs.SchoolID
AND cp.PupilID = pcs.PupilID
LEFT OUTER JOIN LookupDetails AS pcsygld ON pcsygld.LookupDetailsID = pcs.YearGroup
AND pcsygld.LookupID = '3004'
AND ppd.PupilID = cp.PupilID --you were missing cp.PupilID
INNER JOIN win2k12sql.USERFILE.dbo.pupil p ON p.PupilID = user_file_userid
WHERE ('%wc%' = '%wc%') --This doesn't make any sense. You are comparing two string literals.