问题理解内部连接或左连接

时间:2016-06-08 16:11:42

标签: mysql outsystems

我在理解内部和左边的连接时遇到了问题

我在outystems中有以下查询

 SELECT {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments]
      , {CLD}.[LastUpdateOn],min({Project}.[Number])
      ,count({Project}.[Number])
 FROM {CLD}
     INNER JOIN {Project} ON  {Project}.[Id] = {CLDProjects}.[ProjectId] 
     INNER JOIN {CLDProjects} ON {CLD}.[Id] = {CLDProjects}.[CLDId]
 WHERE 
   (
     @IsJAXPM =1 
     or EXISTS (SELECT 1 
             FROM {CLDParticipant} 
             WHERE {CLDParticipant}.[CLDId] = {CLD}.[Id] 
               AND {CLDParticipant}.[UserId] = @UserId) 
     or EXISTS (SELECT 1 
                FROM {ProjectParticipantWidget} 
                    INNER JOIN {ProjectParticipant} ON {ProjectParticipantWidget}.[ProjectParticipantId] =  {ProjectParticipant}.[Id]
                WHERE {ProjectParticipant}.[ProjectId] = {Project}.[Id] 
                  AND {ProjectParticipant}.[UserId] = @UserId)
   )
 GROUP BY {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments], {CLD}.[LastUpdateOn]

问题是Select正在拉动所有CLD元素而不考虑Project,我试图选择其Project ID = Project.Id的CLD。我尝试了两个连接,但它继续拉动所有值 下面是结构的样子 enter image description here

3 个答案:

答案 0 :(得分:2)

请尝试以下操作:首先获取与Project匹配的CLDProjects,然后从匹配的记录中获取CLD。

FROM {CLD} INNER JOIN (
    {CLDProjects} INNER JOIN {Project} ON  {Project}.[Id] = {CLDProjects}.[ProjectId]
  ) ON {CLD}.[Id] = {CLDProjects}.[CLDId]

答案 1 :(得分:1)

您可能错过了ProjectParticipant子查询中CLDProjects的内部联接。添加

INNER JOIN {CLDProjects} ON {ProjectParticipant}.[ProjectId] =  {CLDProjects}.[ProjectId])

在第二个EXISTS连接条件上,否则第二个结果将匹配用户所在的每个项目的存在,忽略CLDProjects上的其他条件。请尝试以下方法:

SELECT {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments]
      , {CLD}.[LastUpdateOn],min({Project}.[Number])
      ,count({Project}.[Number])
 FROM {CLD}
     INNER JOIN {Project} ON  {Project}.[Id] = {CLDProjects}.[ProjectId] 
     INNER JOIN {CLDProjects} ON {CLD}.[Id] = {CLDProjects}.[CLDId]
 WHERE 
   (
     @IsJAXPM =1 
     or EXISTS (SELECT 1 
             FROM {CLDParticipant} 
             WHERE {CLDParticipant}.[CLDId] = {CLD}.[Id] 
               AND {CLDParticipant}.[UserId] = @UserId) 
     or EXISTS (SELECT 1 
                FROM {ProjectParticipantWidget} 
                    INNER JOIN {ProjectParticipant} ON {ProjectParticipantWidget}.[ProjectParticipantId] =  {ProjectParticipant}.[Id]

                    INNER JOIN {CLDProjects} ON {ProjectParticipant}.[ProjectId] =  {CLDProjects}.[ProjectId]

                WHERE {ProjectParticipant}.[ProjectId] = {Project}.[Id] 
                  AND {ProjectParticipant}.[UserId] = @UserId)
   )
 GROUP BY {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments], {CLD}.[LastUpdateOn]

另外..确保你没有将@IsJAXPM传递为1 ...否则它肯定会返回所有记录。 如果有效,请告诉我们。否则,请扩展图表以显示ProjectParticipant和ProjectParticipantWidget表。

答案 2 :(得分:0)

我认为你只需要重新排序你的连接,我试图重现你的情况(连接顺序不正确),但它在测试查询时给我错误,enter image description here

enter image description here

但是如果你重新排序连接,它就可以了。请注意我使用的是OutSystems 10