简体   繁体   中英

MySQL Query to get rank based on the most voted photos of an user

right now I'm using this query to get the rank of the user. The problem is that it uses all the votes from all his photos to get his rank. I want the query to only use his top voted photo to calculate his rank.

Here is the original query, any help would be very very appreciated:

            select WrappedQuery.*
            from (
                select
                  @rownum := @rownum +1 as rank,
                  prequery.user_id,
                  prequery.vote_count
                from
                  ( select @rownum := 0 ) sqlvars,
                    ( SELECT user_id, count(id) vote_count
                      from votes
                      where theme_id = '$currentTheme->id'
                      group by user_id
                      order by count(id) desc) prequery
                  ) WrappedQuery
            where WrappedQuery.user_id = '$me->id'

I tried to make a LIMIT 0, 1 in the prequery but didn't work.

Thanks a lot.

If you are looking for a specific photo, then ignore grouping by the person, but the specific element, THEN roll-back that information to get the user. Your use of sqlvars @rownum principle will remain the same.

Have your inner query be more like (guessing on column name of specific "Photo_ID" would be in the table also)

select
       @rownum := @rownum +1 as rank,
       prequery.user_id,
       prequery.photo_ID,
       prequery.vote_count
   from
      ( select 
              v.User_ID,
              v.Photo_ID, 
              count(*) as Vote_Count
           from 
              IsItStillTheVotesTable v
           group by 
              v.User_ID,
              v.Photo_ID
           order by 
              count(*) desc ) as prequery,
      ( select @rownum := 0 ) sqlvars
   HAVING
      prequery.user_id = '$me->id'
   LIMIT 
      0,1

The "prequery" will already return the records in proper descending order ranked sequence. Then, you have to apply the @rownum to all rows possible and apply a HAVING clause. The Where clause typically pre-checks if a record qualified for the result set and throws out if not before the @rownum would get assigned. The HAVING clause allows the record to have the @rownum get applied, THEN look at it for your "user_ID" and if not, throws it out. This way, you'll get your rank on the specific combination of user AND specific photo.

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