mysql 在另一个选择组中选择 : how many people in downline?

标签 mysql select group-by

你好,我有一张类似于这张的 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/

相关文章:

sql-server - 选择顶部到不同的变量中

mysql - sql查询以从5个表中获取数据

javascript - 对数组项进行分组,但关键是数组

php - 向用户显示脚本正在加载

sql - 使用 perl 自动执行 sql 连接

Jquery 添加一个选项来选择

php - MySQL 查询分组依据和位置

function - julia lang - 如何将多个函数应用于一个值

python - 为什么我会遇到此失败以及为什么 mysql 设置为 false?

php - laravel 5 中的 Multi-Tenancy 应用程序?