2013-10-28 35 views
0

我試圖做到這一點:mysql的,爲了子查詢計數

SELECT 
    id, user_id, roi, 
    (select count(id) from main_ub U where U.user_id=W.user_id and U.cons > 0) as COUNT 
FROM 
    main_stats W 
WHERE 
    week=43 and year=2013 and votes > 2 and COUNT >= 20 
ORDER BY 
    roi desc 
LIMIT 1 

,但我總是得到這樣的錯誤:

#1054 - Unknown column 'COUNT' in 'where clause'

是否可以使用內部的選擇在我的WHERE條款?

+2

中不能使用計數where子句。 –

+0

只需在WHERE語句中使用相同的子查詢而不是COUNT – valex

回答

1
SELECT * FROM 

(SELECT 
    id, user_id, roi, 
    (select count(id) from main_ub U where U.user_id=W.user_id and U.cons > 0) as COUNT 
FROM 
    main_stats W 
WHERE 
    week=43 and year=2013 and votes > 2) res 

WHERE res.COUNT >= 20 
ORDER BY 
    res.roi desc 
LIMIT 1 
+0

這兩個答案都是正確的,但執行速度更快,因此我必須接受此問題。謝謝! – xpanta

1

您不能在您的WHERE子句中使用別名。你必須使用整個表達式,像這樣:

SELECT id, 
    user_id, 
    roi, 
    (
     SELECT count(id) 
     FROM main_ub U 
     WHERE U.user_id = W.user_id 
      AND U.cons > 0 
     ) AS COUNT 
FROM main_stats W 
WHERE week = 43 
    AND year = 2013 
    AND votes > 2 
    AND (
     SELECT count(id) 
     FROM main_ub U 
     WHERE U.user_id = W.user_id 
      AND U.cons > 0 
     ) >= 20 
ORDER BY roi DESC LIMIT 1