我的表格中有invite_code
和invited_by
列。
我想选择所有用户以及此用户邀请的用户数。这可以在一个查询中完成吗?
e.g。我有这些数据:
id | invite_code | invited_by
-----------------------------
1 | 11 |
2 | 22 | 11
3 | 33 | 11
4 | 44 | 22
我想在结果中添加select count(*) from users where u.invite_code = invited_by
:
id | invite_code | invited_by | invite_num
------------------------------------------
1 | 11 | | 2
2 | 22 | 11 | 1
3 | 33 | 11 | 0
4 | 44 | 22 | 0
我正在使用MySQL
答案 0 :(得分:1)
试试这个:
<div id="overlay"></div>
<div id="top_menu">
<span>fasdfsfafasdfas</span>
</div>
答案 1 :(得分:0)
您也可以使用连接而不是列列表中的子查询:
select u1.id, u1.invite_code, u1.invited_by, u2.invite_num
from users u1
left join (select invited_by, count(*) as invite_num from users group by invited_by) u2
on u1.invite_code = u2.invited_by;
答案 2 :(得分:0)
最有效的方法是使用自我加入:
select u.id, u.invite_code, u.invited_by, count(u2.id) as invite_num
from user u
left outer join user u2 on u2.invited_by = u.invite_code
group by u.id, u.invite_code, u.invited_by