2012-05-05 27 views
2

我正在寫一個mysql查詢並出錯。MYSQL中IF條件的別名

「未知列‘逸’在‘字段列表’」由於發生在MySQL中使用別名IF條件

此錯誤。

這是MySQL查詢:

SELECT 
    nCustomerID, 
    dDateRegistered, 
    (select count(nPlayerID) from credit_logs 
     where nPlayerID=nCustomerID) as total_clog, 
    (select count(nPlayerID) FROM bl_transaction_history 
     where nPlayerID=nCustomerID) as total_tran, 
    (select count(nCustomerID) from customer_freeplays 
     where nCustomerID=nCustomerID) as total_free, 
    (select dDateAdded from bl_transaction_history 
     where nPlayerID=nCustomerID) as dat, 
    (select DATEDIFF(now(),dat)/30) as date_differece1, 
    (select DATEDIFF(now(),dDateRegistered)/30) as date_difference2, 
    IF (dat IS NOT NULL,(select DATEDIFF(now(),dat)/30), 
     (select DATEDIFF(now(),dDateRegistered)/30)) as date_difference 
FROM bl_customers 
WHERE nAccountStatus=1 
    and bDeleted=0 
having total_clog>0 
    or total_tran>0 
    or total_free>0 

任何幫助將appriciated .. :)提前

感謝。

+0

'where nCustomerID = nCustomerID'可能需要更正。 –

回答

5

在您選擇其他列時,不能使用別名列。您需要一遍又一遍複製您正在別名的查詢的整個部分。即。在你的初始聲明之後,用(選擇dDateAdded from bl_transaction_history,其中nPlayerID = nCustomerID)替換所有出現的dat。

+0

@Sanjay:您不能在另一列計算或WHERE子句中使用列別名。在這裏看到我的答案:[在where子句中使用'case expression列](http://stackoverflow.com/questions/6545664/using-case-expression-column-in-where-clause/6545685#6545685)另一個解決方法。 –