加入的TSQL选择标准 - 左连接

时间:2015-12-17 21:16:08

标签: sql-server tsql join

Select  *
From    cacheAttendanceMeasures cam 
        Left Join dmcUserSelectedAttendanceMeasures usam on usam.attMeasureID = cam.attMeasureID
          And usam.personID = @personID
          And usam.pageID = @pageID

据我所知,上述查询将返回cacheAttendanceMeasures中的所有行以及条件匹配的dmcUserSelectedAttendanceMeasures和dmcUserSelectedStudentMonths中的所有行。我真正希望它做的是:

  1. 如果左连接不匹配,则返回cacheAttendanceMeasures中的所有行 - 所以它当前正在做什么
  2. 但是,如果左连接匹配,则只返回与cacheAttendanceMeasures匹配的行
  3. 这可能吗?

    修改 我将上面的查询简化为只包含一个Left Join表,我不想让问题过于复杂。

    下面是我希望看到的数据集示例,如果表之间没有匹配,那么匹配就是这样:

    凸轮表
    CID attMeasureID价值
    1个1 530
    2个2 95.7
    3个3 380
    4个4 742.57
    5 5 200

    usam表
    UID PERSONID的pageID attMeasureID
    1 877450 31 1
    2 923450 28 2
    3 877450 31 3
    4 369842 28 4
    5 212193 25 1

    如果@personID = 577597&amp ;,则返回数据集@pageID = 20:
    CID attMeasureID价值UID的pageID attMeasureID
    1 1 530空NUL空
    2 2 95.7空空空
    3 3 380空空空
    4 4 742.57空空空
    5 5 200 null null null

    如果@personID = 877450&amp ;,则返回数据集@pageID = 31:
    CID attMeasureID价值UID PERSONID的pageID attMeasureID
    1 1 530 1 877450 31 1
    3 3 380 3 877450 31 3

1 个答案:

答案 0 :(得分:0)

我不确定你想要的结果......

起初我觉得可能是这样的......

SELECT  *
FROM cacheAttendanceMeasures cam 
LEFT JOIN dmcUserSelectedAttendanceMeasures usam 
   on usam.attMeasureID = cam.attMeasureID
  And usam.personID = @personID
  And usam.pageID = @pageID
LEFT JOIN dmcUserSelectedStudentMonths ussm 
   on ussm.monthSeq = cam.pupilMonth
  And ussm.personID = USAM.PersonID
  And ussm.pageID = USAM.PageId

- 这个where子句似乎很愚蠢,因为它否定了左连接;使它们成为内部连接并违反了你所追求的内容。所以我不认为这就是你所追求的......

WHERE ussm.personID is not null
and usam.personID is not null

因此,对于规则2,您是说......如果单个记录不为空,那么只返回左连接表和第一个表中存在的记录吗?

所以给出:

T1  T2   T3
X   X    X
Y   NULL Y
Z   Y    NULL
T   NULL NULL

我想你只想记录X. 但鉴于此 所以给出:

T1  T2   T3
X   X    NULL
Y   NULL Y
Z   Y    NULL
T   NULL NULL

我想你会想要X,Y Z和T ......需要更好的苛刻。