2013-06-05 52 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