同一个表上的mysql小计数问题

时间:2013-08-07 01:06:59

标签: mysql

请查找db结构如下......

| 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

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

3 个答案:

答案 0 :(得分: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。除非您想删除重复项,否则似乎没有必要。

答案 1 :(得分: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

答案 2 :(得分: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;

<强> Fiddle for your data

<强> Fiddle with more data