2011-10-16 48 views
5

雖然使用下面的查詢, 我得到的錯誤「#1054 - 未知列」在別名與查詢一起使用時出錯?

#1054 - Unknown column 'plus' in 'field list' 
當使用 plus-minus

。否則,查詢運行良好。我想有些東西與我不知道如何使用別名有關。請指導!

謝謝。

查詢:

SELECT users.name, 
count(*) as total, 
SUM(sms.views)+ SUM(sms.downloads)+ (SELECT count(*) FROM `smsfb` WHERE (`feedback`=1 OR `feedback`=100) AND userid=users.uniqueID) AS plus, 
SUM(sms.delreq)+(SELECT count(*) FROM `smsfb` WHERE (`feedback`=5 OR `feedback`=6) AND userid=users.uniqueID) AS minus, 
plus-minus 
FROM sms,users 
WHERE sms.deviceID=users.uniqueID AND sms.catid!=23 AND sms.catid!=44 AND sms.catid!=45 
AND date>="2011-10-03" AND date<"2011-10-09" 
GROUP BY users.uniqueID HAVING total>10 ORDER BY total DESC LIMIT 0, 10 
+1

你能描述一下短信和用戶表嗎? –

回答

9

你不能使用列的別名查詢的選擇部分內。

你可以這樣做:

SELECT name 
    , total 
    , plus 
    , minus 
    , plus - minus 
FROM (
    SELECT users.name, 
    count(*) as total, 
    SUM(sms.views)+ SUM(sms.downloads)+ (SELECT count(*) FROM `smsfb` WHERE  (`feedback`=1 OR  `feedback`=100) AND userid=users.uniqueID) AS plus, 
    SUM(sms.delreq)+(SELECT count(*) FROM `smsfb` WHERE (`feedback`=5 OR `feedback`=6)  AND  userid=users.uniqueID) AS minus 
    FROM sms,users 
    WHERE sms.deviceID=users.uniqueID 
     AND sms.catid!=23 AND sms.catid!=44 
     AND sms.catid!=45 
     AND date>="2011-10-03" AND date<"2011-10-09" 
    GROUP BY users.uniqueID HAVING total>10 ORDER BY total DESC 
    LIMIT 0, 10 
) plusAndMinus 

Problems with Column Aliases

您可以使用GROUP BY,ORDER BY或HAVING子句中的別名來引用列

+0

仍然完全一樣的錯誤! (Pl。Nt .:我複製粘貼你的查詢,因爲它) – BufferStack

+0

對不起@Tajar,我忘了在內部查詢中刪除'plus-minus'。現在就試試。 – DavidEG

+0

謝謝!很有幫助...學習了一些新的需要一次又一次! – BufferStack