右连接不返回所有预期的行

时间:2013-09-13 10:51:11

标签: sql

我在HP ALM(正式的质量中心)中运行了两个查询:

查询1:

SELECT 
TEST.TS_NAME
FROM CYCLE
JOIN TESTCYCL ON (TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID)
JOIN TEST ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID)
WHERE CYCLE.CY_CYCLE_ID = 44451

这将返回38行,其中包含我要报告的所有测试名称。

查询2:

SELECT 
STEP.ST_RUN_ID as "RunId" /*Test Step.Run No*/ ,
TEST.TS_NAME as "Test Name",
STEP.ST_STATUS as "Run Status",
STEP.ST_STEP_NAME as "Step Name",
CYCLE.CY_CYCLE as "TestSet",
CYCL_FOLD.CF_ITEM_NAME  as "Test Lab Folder Name"
FROM RUN, CYCL_FOLD, CYCLE, STEP, TEST
WHERE RUN.RN_CYCLE_ID = CYCLE.CY_CYCLE_ID
AND CYCLE.CY_FOLDER_ID = CYCL_FOLD.CF_ITEM_ID
AND CYCLE.CY_CYCLE_ID = 44451
AND STEP.ST_RUN_ID = RUN.RN_RUN_ID
AND RUN.RN_TEST_ID = TEST.TS_TEST_ID
AND RUN.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN
GROUP BY RN_TESTCYCLE_ID)

此查询返回具有各个步骤及其状态的所有测试。 MAX语句返回该测试的最新运行。

运行测试时,在STEP表中分配RUN_ID。问题是如果没有运行测试,它将没有RUN_ID,因此不会包含在结果中。

所以我创建了以下查询3:

SELECT
STEP.ST_RUN_ID as "RunId" /*Test Step.Run No*/,
TEST.TS_NAME as "Test Name",
STEP.ST_STATUS as "Run Status",
STEP.ST_STEP_NAME as "Step Name",
CYCLE.CY_CYCLE as "TestSet",
CYCL_FOLD.CF_ITEM_NAME  as "Test Lab Folder Name" 
FROM RUN, CYCL_FOLD, CYCLE, STEP, TEST
    RIGHT JOIN (
          SELECT 
          TEST.TS_NAME
          FROM CYCLE
          JOIN TESTCYCL ON (TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID)
          JOIN TEST ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID)
          WHERE CYCLE.CY_CYCLE_ID = 44451) alltest 
          ON alltest.TS_NAME = TEST.TS_NAME
WHERE RUN.RN_CYCLE_ID = CYCLE.CY_CYCLE_ID
AND CYCLE.CY_FOLDER_ID = CYCL_FOLD.CF_ITEM_ID
AND STEP.ST_RUN_ID = RUN.RN_RUN_ID
AND RUN.RN_TEST_ID = TEST.TS_TEST_ID
AND RUN.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN GROUP BY rn_testcycl_id)

我想在所有测试中使用RIGHT JOIN并填充已记录运行但仍未返回NULL行的行。运行查询2或3之间没有区别。

2 个答案:

答案 0 :(得分:1)

它没有返回行,因为where子句正在过滤它们。

使用ANSI标准join语法(on子句)并将条件放在on子句中。结果是这样的:

SELECT s.ST_RUN_ID as "RunId" /*Test Step.Run No*/, t.TS_NAME as "Test Name",
       s.ST_STATUS as "Run Status", s.ST_STEP_NAME as "Step Name", c.CY_CYCLE as "TestSet",
       cf.CF_ITEM_NAME  as "Test Lab Folder Name" 
FROM RUN r join
     CYCL_FOLD cf
     on c.RN_CYCLE_ID = cf.CY_CYCLE_ID join
     CYCLE c
     on c.CY_FOLDER_ID = cf.CF_ITEM_ID join
     STEP s
     on s.ST_RUN_ID = r.RN_RUN_ID join
     TEST t
     on r.RN_TEST_ID = t.TS_TEST_ID right join
     (SELECT TEST.TS_NAME
      FROM CYCLE JOIN
           TESTCYCL
           ON TESTCYCL.TC_CYCLE_ID = CYCLE.CY_CYCLE_ID JOIN
           TEST
           ON TEST.TS_TEST_ID = TESTCYCL.TC_TEST_ID
      WHERE CYCLE.CY_CYCLE_ID = 44451
     ) alltest 
     ON alltest.TS_NAME = t.TS_NAME and
        r.RN_RUN_ID in (select MAX(RUN.RN_RUN_ID) FROM RUN GROUP BY rn_testcycl_id);

答案 1 :(得分:-3)

如果要获取空值,请执行右外连接,而不是右连接..