0

请找到以下数据库结构...

| id | account_number  | referred_by  |
+----+-----------------+--------------+
|  1 | ac203003        | ac203005     |
+----+-----------------+--------------+
|  2 | ac203004        | ac203005     |
+----+-----------------+--------------+
|  3 | ac203005        | ac203004     |
+----+-----------------+--------------+

我想达到以下结果...

id, account_number, total_referred 
1,  ac203005, 2
2, ac203003m 0
3, ac203004, 1

我正在使用以下查询...

SELECT id, account_number, 
(SELECT count(*) FROM `member_tbl` WHERE referred_by = account_number) AS total_referred
FROM `member_tbl`
GROUP BY id, account_number

但它没有给出预期的结果,请帮忙。谢谢。

4

3 回答 3

0

一个想法是自己加入表格。这样你就可以避免子查询。这种方法可能会提高性能。

select b.id, b.account_number, count(a.referred_by) 
from member_tbl a inner join member_tbl b 
on a.referred_by=b.account_number 
group by (a.referred_by);

SQL小提琴:http ://sqlfiddle.com/#!2/b1393/2

另一个测试,有更多数据:http ://sqlfiddle.com/#!2/8d216/1

于 2013-08-07T01:14:41.943 回答
0
select t1.account_number, count(t2.referred_by)
from (select account_number from member_tbl) t1
left join member_tbl t2 on
t1.account_number = t2.referred_by
group by t1.account_number;

小提琴你的数据

摆弄更多数据

于 2013-08-07T07:16:58.953 回答
0

您需要使用表别名来正确执行此操作:

SELECT id, account_number, 
       (SELECT count(*)
        FROM `member_tbl` t2
        WHERE t2.referred_by = t1.account_number
       ) AS total_referred
FROM `member_tbl` t1;

您原来的查询有referred_by = account_number. 如果没有别名,这些将来自同一行 - 并且值为0.

另外,我删除了外部group by. 除非您想删除重复项,否则似乎没有必要。

于 2013-08-07T01:10:31.380 回答