如何编写嵌套查询连接三个表?

时间:2016-04-04 08:04:13

标签: sql sql-server sql-server-2008

我正在创建一个类似社交网络的网站。我有3张桌子。我发现每个用户及其朋友总数和被阻止的朋友数量。

    1. tbl_Registrations

    |   Id  |   FirstName   |
    *************************
        1       User1   
        2       User2
        3       User3   
        4       User4
        5       User5
        6       User6
        7       User7
        8       User8


    2.tbl_Friends

    |   Id  |   SenderId    |   ReciverId   |  Status   |

        1           1               2          Accept
        2           3               1          Accept
        3           4               1          Accept
        4           2               3          Accept
        5           3               8          Accept
        6           4               2          Accept  
        7           4               3          Accept
        8           8               4          Accept

  3. tbl_Status

   |    Id  |   UserId  |   Status  |

        1         1         Blocked
        2         3         Blocked
        3         4         Allowed
        4         2         Blocked
        5         6         Blocked
        6         5         Allowed
        7         8         Blocked
        8         7         Allowed

我的查询是

SELECT tbl_Registrations.FirstName, COUNT(*) AS TotalFriends
FROM tbl_Friends INNER JOIN tbl_Registrations ON tbl_Friends.SenderId = tbl_Registrations.Id 
OR tbl_Friends.ReciverId = tbl_Registrations.Id
WHERE (tbl_Friends.Status = 'Accept')
GROUP BY tbl_Registrations.FirstName

使用我的查询我将只获得姓名和朋友总数。如何在同一查询中包含查找被阻止的朋友的数量。

我的预期输出是

|    FirstName   |  TotalFriendsCount   |    BlockedFriendsCount   |

1 个答案:

答案 0 :(得分:0)

试试这个

 SELECT tbl_Registrations.FirstName, 
        COUNT(*) AS TotalFriends,
        (   SELECT COUNT(*) FROM tbl_Status
            WHERE [Status]  = 'Blocked'
                AND (UserId = tbl_Friends.SenderId
                    OR UserId = tbl_Friends.ReciverId)
                AND UserId <> tbl_Registrations.id ) BlockedFriendsCount
FROM tbl_Friends 
INNER JOIN tbl_Registrations ON tbl_Friends.SenderId = tbl_Registrations.Id 
    OR tbl_Friends.ReciverId = tbl_Registrations.Id
WHERE (tbl_Friends.Status = 'Accept')
GROUP BY tbl_Registrations.FirstName