自我加入Mysql中的Count

时间:2014-11-20 03:47:45

标签: mysql join count self

我有一张看起来像这样的表

ID     fname      lname      sponsor_id
1       Joe       Smith         0
2      John       Jones         1
3       Sue       Wills         1
4       Bob       Hass          3

我想按降序排列所有领导者

ID   fname       lname      number_sponsored
1     Joe        Smith            2
3     Sue        Wills            1
2     John       Jones            0
4     Bob         Hass            0

我不能为我的生活弄清楚这个加入。 有人想对此嗤之以鼻吗?

3 个答案:

答案 0 :(得分:2)

我认为这里唯一的技巧是你需要一个left join来获得零计数的行。以下是编写查询的一种方法:

select t.id, t.fname, t.lname, count(t2.sponsor_id) as num_sponsored
from table t left join
     table t2
     on t.id = t2.sponsor_id
group by t.id, t.fname, t.lname;

另一种方法不使用明确的join

select t.*, (select count(*) from table t2 where t.id = t2.sponsor_id) as num_sponsored
from table t;

对于那些对这个问题有点困惑的人来说,这可能更清楚。

答案 1 :(得分:0)

您可以计算子查询中赞助的数字

 Select Id, fname, lname, 
( select count(sponser_id) from    table1 a where a.sponser_id = b.id) as number_sponsored
From table1 b
Order by number_sponsored desc

答案 2 :(得分:0)

SELECT DISTINCT 
      id 
FROM
   tbl t
Left JOIN 
   (SELECT 
       number_sponsored,
       COUNT(DISTINCT id) AS number_sponsored 
   FROM
       tbl2
   GROUP BY   sponsor_id) AS number_sponsored 
   ON t.id = number_sponsored.id 
  Where t.sponsor_id >t2. number_sponsored 

或者您可以查看此资源

SELECT * FROM t1
  ORDER BY key_part1,key_part2,... ;

SELECT * FROM t1
  WHERE key_part1 = constant
  ORDER BY key_part2;

SELECT * FROM t1
  ORDER BY key_part1 DESC, key_part2 DESC;

SELECT * FROM t1
  WHERE key_part1 = 1
  ORDER BY key_part1 DESC, key_part2 DESC;

SELECT * FROM t1
  WHERE key_part1 > constant
  ORDER BY key_part1 ASC;

SELECT * FROM t1
  WHERE key_part1 < constant
  ORDER BY key_part1 DESC;

SELECT * FROM t1
  WHERE key_part1 = constant1 AND key_part2 > constant2
  ORDER BY key_part2;

参考:http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html