简体   繁体   中英

MySQL Select Items where Count (from another table) is greater than X

The following situation: I have a list of users and outfits, each user can create N outfits. Users can vote for their outfit.

Now I want to list all outfits and users. This works fine. But if I want to list all outfits of each each / all users WHERE the amount of required votes is reached. So WHERE count_votes > required_votes.

Thats what I've got but it obviously gives me an error:

SELECT ay_users.*, 
       ay_users_outfits.*, 
       COUNT(ay_votes.voteId) AS countvotes 
FROM   ay_users_outfits, 
       ay_users, 
       ay_votes
WHERE  ay_users_outfits.outfitUserId = ay_users.userId 
AND    ay_votes.voteOutfitId = ay_users_outfits.outfitId 
AND    ay_users_outfits.outfitRequiredVotes <= countvotes
ORDER BY ay_users_outfits.outfitCreationDate ASC

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

What am I doing wrong?

Take a look at this: http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html

You will need to use a HAVING clause, something like

SELECT 
    ay_users . *,
    ay_users_outfits . *,
FROM
    ay_users_outfits,
    ay_users,
    ay_votes
WHERE
    ay_users_outfits.outfitUserId = ay_users.userId AND 
    ay_votes.voteOutfitId = ay_users_outfits.outfitId

GROUP BY ay_users.userId
HAVING ay_users_outfits.outfitRequiredVotes <= COUNT(ay_votes.voteId)
ORDER BY ay_users_outfits.outfitCreationDate ASC

The reason is that no column countvotes exists and you are using it in your where clause...

you will have to use COUNT(ay_votes.voteId) in your where clause.

AND    ay_users_outfits.outfitRequiredVotes <= COUNT(ay_votes.voteId)

You cannot use (named) calculations in your where clause

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