查询Sql连接

时间:2010-01-04 12:19:44

标签: sql sql-server sql-server-2005

我有三张桌子。

  

tblLink:(LinkId,LinkName,GroupId,SubGroupId)
            GroupId和SubGroupId是tblGroup和tblSubGroup中的外键   tblGroup:(GroupId,GroupName)
  tblSubGroup:(SubGroupId,SubGroupName)

在tblLink中允许SubGroupId为Null但GroupId是强制性的。

我想为tblLink中的每个LinkId获取LinkName,GroupName,SubGroupName 我写了一个查询

  

SELECT L.LinkName,G.GroupName,SG.SubGroupName FROM tblLink L
                                          左加入
                                                       tblSubGroup SG
                                          ON
                                                      (L.SubGroupId = SG.SubGroupId)
                                          内部加入
                                                      tblGroup G
                                          ON
                                                      (L.GroupId = G.GroupId)

如果某些LinkId没有子组,我想显示 NotExist 而不是 Null

1 个答案:

答案 0 :(得分:4)

SELECT
    L.LinkName, G.GroupName, 
    ISNULL(SG.SubGroupName, 'NotExist') AS SubGroupName
FROM
    Link L
....