我有3个表,一个用于Study,其他是Travel和Country.Study。
Study
表包含StudyID,StartDate,EndDate,CountryID
,并将StudyID
设为primary key
。
Travel
表包含TravelID,StudyID,CountryID,TravelStartDate,TravelEndDate
,TravelID
为Primary key
,StudyID
为Foreign 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
我想显示CountryName
和Travel
的{{1}}。如何显示一个国家的旅行和一个学习?
答案 0 :(得分: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
答案 1 :(得分: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