在COUNT LEFT JOIN上找不到列

时间:2014-12-09 07:52:38

标签: php mysql yii

我试图通过加入介绍公司来搜索用户,并使用以下代码计算总充值交易

$data = Yii::app()->db->createCommand()->select('a.Id, a.UserName, a.Name, a.Sex, a.DOB, a.Email, a.ContactNo, a.Credit, a.EmailVerified, a.Level, a.CreatedTime, a.Active, a.Referral, a.ReceivedFirstTimeDepositBonus, b.Name AS ReferralName, COUNT(c.Id) AS TransactionCount')->from('user a')->leftJoin('company b', 'a.Referral=b.Id')->leftjoin('transaction c', 'a.Id = c.UserId')->group('a.Id');

$data = $data->andWhere('a.Role = 0');
$data = $data->andWhere('c.TransactionCount > 0');
$data = $data->queryAll();

但是yii给我这样的错误

  

找不到列:1054未知列&c; .TransactionCount'在'哪里   条款&#39 ;.执行的SQL语句是:SELECT a.Id,a.UserName,   a.Name,a.Sex,a.DOB,a.Email,a.ContactNo,a.Credit,a.EmailVerified,   a.Level,a.CreatedTime,a.Active,a.Referral,   a.ReceivedFirstTimeDepositBonus,b.Name AS ReferralName,COUNT(c.Id)   AS TransactionCount FROM user a LEFT JOIN company b ON   a.Referral = b.Id LEFT JOIN transaction c ON a.Id = c.UserId WHERE   (a.Role = 0)AND(c.TransactionCount> 0)GROUP BY aId ORDER BY   Id限制20

我试着长时间查看查询,但我不知道问题是什么我不知道为什么它会让我犯错误,即使我尝试

$data = $data->andWhere('TransactionCount > 0');

但是只有列名不同才能得到相同的错误

3 个答案:

答案 0 :(得分:1)

您不能在WHERE子句中使用别名。

更换

$data = $data->andWhere('c.TransactionCount > 0');

$data = $data->having('COUNT(c.Id) > 0');

$data = $data->having('TransactionCount > 0');

应该这样做。

答案 1 :(得分:0)

您的TransactionCount不是真正的列,而是查询执行后的产品。这就是SQL无法找到它的原因。

c.TransactionCount > 0替换为COUNT(c.Id) > 0
或者更好地使用HAVING TransactionCount > 0In Yii having看起来像->having('TransactionCount > :desiredCount', [':desiredCount' => 0])

答案 2 :(得分:0)

cluase始终在group_by --aggregate函数

之前执行

SELECT a.Id,a.UserName,a.Name,a.Sex,a.DOB,a.Email,a.ContactNo,a.Credit,a.EmailVerified,a.Level,a.CreatedTime,a。 Active,a.Referral,a.ReceivedFirstTimeDepositBonus,b.Name AS ReferralName,COUNT(c.Id)AS TransactionCount FROM user LEFT JOIN company b ON a.Referral = b.Id LEFT JOIN transaction c ON a.Id = c。 UserId WHERE(a.Role = 0)AND(count(c.Id)> 0)GROUP BY a.Id ORDER BY Id LIMIT 20