-1

我有 3 张桌子,一张是用来学习的,另外一张是 Travel 和 Country.Study。 Study 表包含StudyID,StartDate,EndDate,CountryID并设置StudyIDprimary key.

Travel表包含TravelID,StudyID,CountryID,TravelStartDate,TravelEndDate, TravelIDasPrimary keyStudyIDas Foreign key

Country表包含CountryID,CountryCode,CountryName, CountryIDas 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

我想显示CountryNameforTravelStudy. 如何显示一个国家旅行和一个学习?

4

2 回答 2

0

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

SELECT A.CountryID ,B.TravelID,A.StartDate ,A.EndDate ,B.StartDate ,B.EndDate ,C.CountryCode + ' - ' + C.CountryName AS CountryName
从研究 A
        A.StudyID = B.StudyID 上的内部加入旅行 B
        LEFT OUTER JOIN Country C ON A.CountryID = C.CountryID
于 2013-06-05T06:17:05.733 回答
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
于 2013-06-05T05:36:54.503 回答