mysql,按子查询次数排序

时间:2013-10-28 07:00:49

标签: 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
LIMIT 1

但我总是得到这个错误:

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

是否可以在WHERE子句中使用内部选择?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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