这是我的朋友表的示例
ID FRIENDID
1001 1110
1001 1005
1002 1207
1002 1188
1005 1107
1005 1001
我正在尝试回答这些问题。
现在第一个很简单
SELECT count(ID) FROM FRIENDS
WHERE friendID = 1005;
第二个是我想到的
SELECT count(ID) FROM FRIENDS
WHERE friendID IN
(SELECT ID from FRIENDS where friendID = 1005) AND NOT ID = 1005;
第三和第四个我很困惑,想出了这个,但是没有用。不知道什么是对的?我认为我需要在其中使用DISTINCT
,以确保没有重复。
SELECT count(ID) FROM FRIENDS
WHERE friendID IN
((SELECT ID from FRIENDS where friendID = 1005) AND NOT ID = 1005
WHERE friendID IN
(SELECT ID from FRIENDS where friendID = 1005) AND NOT ID = 1005);
答案 0 :(得分:1)
这可以通过count()
函数来完成:
SELECT f1.id, count(DISTINCT f1.friendid) AS friends_cnt
FROM FRIENDS AS f1
WHERE f1.id = 1005;
这可以通过将表与自身连接来完成:
SELECT f1.id, count(DISTINCT f2.friendid) AS f_friends_cnt
FROM FRIENDS AS f1
JOIN FRIENDS AS f2 ON f2.id = f1.frienfid
AND f2.id != f1.id -- to avoid recursion
WHERE f1.id = 1005;
与表本身连接两次:
SELECT f1.id, count(DISTINCT f3.friendid) AS f_f_friends_cnt
FROM FRIENDS AS f1
JOIN FRIENDS AS f2 ON f2.id = f1.frienfid
AND f2.id != f1.id
JOIN FRIENDS AS f3 ON f3.id = f2.frienfid
AND f3.id != f1.id
AND f3.id != f2.id
WHERE f1.id = 1005;
与表本身联接三遍:
SELECT f1.id, count(DISTINCT f4.friendid) AS f_f_f_friends_cnt
FROM FRIENDS AS f1
JOIN FRIENDS AS f2 ON f2.id = f1.frienfid
AND f2.id != f1.id
JOIN FRIENDS AS f3 ON f3.id = f2.frienfid
AND f3.id != f1.id
AND f3.id != f2.id
JOIN FRIENDS AS f4 ON f4.id = f3.frienfid
AND f4.id != f1.id
AND f4.id != f2.id
AND f4.id != f3.id
WHERE f1.id = 1005;
答案 1 :(得分:0)
您可能多次计数同一个朋友,因为同一个人可能是原始人的不同朋友的朋友。
将public class Class_D
{
public string my_field { get; set; }
public List<Class_A> list_A { get; set; }
// etc...
}
List<Class_D> list_D = new List<Class_D>(); //and then populate it
更改为SELECT COUNT(ID)
,它将不会两次计数相同的ID。