作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
你好,我有一张类似于这张的 table :
id sponsor name
------------------------
1 0 Sasha
2 1 John
3 1 Walter
4 3 Ashley
5 1 Mark
6 4 Alexa
7 3 Robert
8 3 Frank
9 4 Marika
10 5 Philip
11 9 Elizabeth
当我选择一个 ID(称之为 MYCHOICE)时,我想知道所有拥有像 MYCHOICE 这样的赞助商的人的名字...很简单:
select * from tablename where sponsor=MYCHOICE
但是……问题来了……我想知道这个结果的下线有多少人……所以……有多少条赞助商的记录,比如每个id。
如果我选择 id 1 结果应该是
id name downline
----------------------
2 John 0 (noone with sponsor=2)
3 Walter 3 (3 with sponsor=3: ashley, robert, frank)
5 Mark 1 (1 with sponsor=5: philip)
如果我选择 id 4 结果应该是
id name downline
----------------------
6 Alexa 0
9 Marika 1 (1 with sponsor=9: Elizabeth)
如果我的选择是 1,我会尝试这个“糟糕的解决方案”
select sponsor,count(*) as downline from tablename where sponsor in (select id from tablename where sponsor=1) group by sponsor order by downline desc
这个查询的结果是
sponsor downline
---------------------
3 3
5 1
有两个问题:- 名字不是权利,也不是我想要的- 示例中的计数 0 "2|John|0"没有出现
谢谢你的建议和帮助,对不起英语,N.
最佳答案
SELECT child.id,
child.name,
COUNT(grandchild.sponsor) downline
FROM TableName child
INNER JOIN TableName parent
ON child.sponsor = parent.id AND
parent.id = ? -- << user choice
LEFT JOIN TableName grandchild
ON child.id = grandchild.sponsor
GROUP BY child.id, child.name
如您所见,该表与自身连接了两次。使用 INNER JOIN
的第一个连接获取与 Sponsor
关联的记录,这是您的 user_choice。使用 LEFT JOIN
的第二个联接获取与您的user_choice 中的记录关联的所有记录。
关于mysql 在另一个选择组中选择 : how many people in downline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186225/
我是一名优秀的程序员,十分优秀!