2013-06-05 54 views
-1

我有3张桌子,一张用于研究,另外一张则是旅行和国家。研究。 Study表包含StudyID,StartDate,EndDate,CountryID并将StudyID设为primary key如何加入3张表

Travel表包含TravelID,StudyID,CountryID,TravelStartDate,TravelEndDateTravelIDPrimary keyStudyIDForeign key

Country表包含CountryID,CountryCode,CountryName, CountryID作为primary key

我想CountryName"CountryCode+' - '+CountryName as CountryName".

我有以下查询:

SELECT 
      Study.CountryID 
         ,Travel.CountryID 
         ,StartDate 
         ,EndDate 
         ,TravelStartDate,TravelEndDate, 
       , CountryCode+' - '+CountryName as CountryName,    

         FROM dbo.Study left join dbo.Countries 
         on 
         Study.CountryID=Countries.CountryID 
        left join Travel 
         on 
        Travel.StudyID=Study.StudyID 

我想显示CountryNameTravelStudy。我如何显示一个国家的旅行和一个用于学习?

回答

0

另外,因为你加入国家研究,然后在旅行,这意味着他们将永远是相同的。

以下应该工作,假设每个表中都有一个值。这是非常未经测试的,但应该指向正确的方向。我认为跨应用需要SQL Server 2005或更高版本。

;with 
GetStudyCountry as 
(
select a.countryCode, a.countryName 
FROM dbo.countries a 
LEFT JOIN dbo.study b on a.countryid = b.countryid 
) 
,GetTravelCountry as 
(
select a.countryCode, a.countryName 
FROM dbo.countries a 
LEFT JOIN dbo.travel b on a.countryid = b.countryid 
) 
select a.CountryID ,b.CountryID ,a.StartDate, a.enddate ,b.TravelStartDate ,b.TravelEndDate, GetTravelCountry.CountryCode + '-' + GetTravelCountry.CountryName as TravelCountryName, GetStudyCountry.CountryID + '-' GetStudyCountry.CountryID as StudyCountryName 
from dbo.study a 
cross apply dbo.travel b 
cross apply GetTravelCountry c 
cross apply GetStudyCountry d 
0

您将所有三个表格相互连接,这意味着它们将始终保持不变。 我想你正在寻找这个结果。 您可以试试这个:

 
SELECT A.CountryID ,B.TravelID,A.StartDate ,A.EndDate ,B.StartDate ,B.EndDate ,C.CountryCode + ' - ' + C.CountryName AS CountryName 
FROM STUDY A 
     INNER JOIN TRAVEL B ON A.StudyID = B.StudyID 
     LEFT OUTER JOIN Country C ON A.CountryID = C.CountryID