不同的用户,友谊和选择

时间:2014-05-11 09:58:54

标签: sql

我有两张桌子:

User:

+----+----------+--+
|    |   User   |  |
+----+----------+--+
| pk | email    |  |
|    | password |  |
|    | ...      |  |
+----+----------+--+

and Friendship:

+----+-------------+--+
|    | FriendShip  |  |
+----+-------------+--+
| pk | user1_email |  |
| pk | user2_email |  |
|    | date        |  |
|    | accepted    |  |
+----+-------------+--+

所以基本上,当有人想和别人交朋友时,我们会把它记录在友谊表中。

现在假设我们想要选择少于3个朋友的所有用户,除了没有朋友的人之外很容易,因为friendship表中没有这个记录。< / p>

我的查询目前看起来像这样:

SELECT u.email, COUNT(u.email) 
FROM user u 
    INNER JOIN friendship f ON f.user1_email = u.email OR f.user2_email = u.email
GROUP BY u.email 
HAVING COUNT(u.email) < 3;

如何添加asocial人员的结果:p?

1 个答案:

答案 0 :(得分:2)

您可以使用UNION快速获得所需内容。

SELECT u.email, COUNT(u.email) 
FROM user u 
INNER JOIN friendship f ON f.user1_email = u.email OR f.user2_email = u.email 
GROUP BY u.email 
HAVING COUNT(u.email) < 3
UNION
SELECT u.email, 0
FROM user u
WHERE u.email not in (SELECT user1_email from friendship) 
AND u.email not in (SELECT user2_email from friendship);