复杂查询 - 获得推荐人数最多的人

时间:2011-11-15 10:19:03

标签: php mysql

我正在尝试进行某种SQL查询,其中我只获得推荐次数最多的10个人,但最少有1个推荐。

我的表格如下:

CREATE TABLE IF NOT EXISTS `beta_list` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(250) NOT NULL,
  `referrer` int(10) NOT NULL,
  `referral_code` int(10) NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

我尝试过这样的事情:

SELECT 
     email,
     referral_code as refcode,
     (SELECT COUNT(*) FROM beta_list WHERE referrer=refcode) as referrals
  FROM 
     beta_list 
  WHERE
     referrals > 0
  ORDER BY
     referrals DESC
  LIMIT
     10

但它只是在'where子句'中说“未知列'引用'。”

我不是sql guru,我只是刚刚开始学习更复杂的SQL查询,所以任何有关如何实现此类目标的帮助都将深表感谢!

干杯!

2 个答案:

答案 0 :(得分:1)

尝试此操作 - 添加外部查询以从内部查询中提取结果 -

select ref.email, ref.refcode, ref.referrals from 
(
  SELECT 
     email,
     referral_code as refcode,
     (SELECT COUNT(*) FROM beta_list WHERE referrer=refcode) as referrals
  FROM 
     beta_list
) as ref
WHERE
     ref.referrals > 0
ORDER BY
     ref.referrals DESC
LIMIT
     10

答案 1 :(得分:1)

放手一搏:

SELECT email,referral_code as refcode,count(*) as referrals
FROM beta_list 
WHERE referrer = referral_code
GROUP BY email,referral_code
ORDER BY referrals DESC
LIMIT 10;