5

我有一个 SQL 查询,我想将两个表连接起来,然后使用该连接表连接第三个表。我尝试用谷歌搜索如何做到这一点,但措辞很尴尬,没有发现任何用处。这是我尝试使用的代码:

SELECT t.id AS ID
, a.id AS ActivityID
, t.ProjectType AS ProjectType
, t.Tier1Mission AS Mission
, m.id ASMissionID
, m.name AS MissionName
, t.Tier2Activity AS Activity
, a.name AS ActivityName
, t.Tier3Project AS Project
FROM tActivity a
 INNER JOIN 
 (SELECT id, name FROM tMission) m
 ON tActivity.missionId = MissionID
 LEFT OUTER JOIN
 (SELECT *
  FROM tTaxonomy
  WHERE Tier1Mission = m.name AND Tier2Activity = a.name)

编辑:我遇到的主要问题是 tActivity 表的条目具有相同的“名称”但引用不同的 MissionId。连接所有表很容易,但需要有正确的 MissionID,关系保存在第三个表“tTaxonomy”中。

4

3 回答 3

5

您几乎拥有它,但需要一个别名和一个ON子句来为子句的第二个连接插入WHERE。此外,在您的第一ON个子句中,使用表别名a而不是原始名称。

SELECT t.id AS ID
, a.id AS ActivityID
, t.ProjectType AS ProjectType
, t.Tier1Mission AS Mission
, m.id ASMissionID
, m.name AS MissionName
, t.Tier2Activity AS Activity
, a.name AS ActivityName
, t.Tier3Project AS Project
FROM 
  tActivity a
  INNER JOIN 
   (SELECT id, name FROM tMission) m
     ON a.missionId = m.id
  LEFT OUTER JOIN
   (SELECT *
     FROM tTaxonomy
   ) t ON t.Tier1Mission = m.name AND t.Tier2Activity = a.name

但是,仔细看一下,我看不到任何需要使用连接子查询的东西。子查询中没有聚合或限制使它们成为必要。您可以只使用普通的表连接:

SELECT t.id AS ID
, a.id AS ActivityID
, t.ProjectType AS ProjectType
, t.Tier1Mission AS Mission
, m.id ASMissionID
, m.name AS MissionName
, t.Tier2Activity AS Activity
, a.name AS ActivityName
, t.Tier3Project AS Project
FROM
  tActivity a
  INNER JOIN tMission m ON a.missionId = m.id
  LEFT JOIN tTaxonomy t ON t.Tier1Mission = m.name AND t.Tier2Activity = a.name
于 2012-10-01T17:46:39.373 回答
2
select t.id as ID,
    a.id as ActivityID,
    t.ProjectType as ProjectType,
    t.Tier1Mission as Mission,
    m.id ASMissionID,
    m.name as MissionName,
    t.Tier2Activity as Activity,
    a.name as ActivityName,
    t.Tier3Project as Project
from tActivity a
inner join tMission m on a.missionId = m.MissionID
left outer join tTaxonomy t on t.Tier1Mission = m.name and t.Tier2Activity = a.name
于 2012-10-01T17:46:55.717 回答
1

看起来你很接近,你JOIN在最后一个错误的地方有语法JOIN

SELECT t.id AS ID
    , a.id AS ActivityID
    , t.ProjectType AS ProjectType
    , t.Tier1Mission AS Mission
    , m.id ASMissionID
    , m.name AS MissionName
    , t.Tier2Activity AS Activity
    , a.name AS ActivityName
    , t.Tier3Project AS Project
FROM tActivity a
INNER JOIN 
(
    SELECT id, name 
    FROM tMission
) m
 ON a.missionId = MissionID
LEFT OUTER JOIN
(
    SELECT *
    FROM tTaxonomy
) t
    on m.name = t.Tier1Mission
    AND a.name = t.Tier2Activity

甚至:

SELECT t.id AS ID
    , a.id AS ActivityID
    , t.ProjectType AS ProjectType
    , t.Tier1Mission AS Mission
    , m.id ASMissionID
    , m.name AS MissionName
    , t.Tier2Activity AS Activity
    , a.name AS ActivityName
    , t.Tier3Project AS Project
FROM tActivity a
INNER JOIN tMission m
    ON a.missionId = MissionID
LEFT OUTER JOIN tTaxonomy t
    on m.name = t.Tier1Mission
    AND a.name = t.Tier2Activity
于 2012-10-01T17:46:48.700 回答