简体   繁体   中英

mysql, order by subquery count

I am trying to do this:

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

but I always get this error:

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

Is it possible to use the inner select in my WHERE clause?

You cannot use aliases in your WHERE clause. You have to use the entire expression, like this:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM