mysql,按子查询计数排序

mysql,按子查询计数排序,mysql,sql,Mysql,Sql,我正在尝试这样做: 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 L

我正在尝试这样做:

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-where子句中的未知列“COUNT”


可以在我的WHERE子句中使用内部select吗?

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

您不能在where子句中使用count。只需在where语句中使用相同的子查询而不是count。两个答案都是正确的,但执行速度更快,因此我不得不接受这一点。非常感谢。
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