Question

Calculating rank of item based on votes in SQL

Asked by: fedders_world

Hey guys,
Im using MySQL with ASP.NET/VB

I have a Table which hold an PictureId as well as a votes coloum.
The votes col stores then number of votes a picture has (its updated everytime someone votes)
For example:
Pictureid        Votes
1                     200

I am retriving this using Select PictureId, Votes FROM Picture_Count WHERE Pictureid =
What i would like to be able to do, in an SLQ query is also give a rank.
Example:
If a picture has 200 votes its ranked 1, and if it has 201 votes it is ranked second. I want to be able to return this in the results so that i can display it in a datalist.

Thanks in advnace
Feds

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-06-21 at 23:56:38ID22650637
Tags

rank

,

calculate

,

mysql

Topics

Programming for ASP.NET

,

MySQL Server

Participating Experts
2
Points
250
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Ranking & sorting Votes on MySQL
    Hi, I need to be able to display the following "Rank #" anywhere attached to a QUESTION review..now this should correspond to the place of this review on my SQL list... for example if i sort my list by RATE ascending I should get a line number which corresponds to ...
  2. Ranking Results
    I have been messing around with this for a whole day and cannot figure it out. SELECT COUNT(*) AS user_rank FROM rp_user_account AS a INNER JOIN rp_user_account AS b ON a.rank_overall >= b.rank_overall AND b.user_username = '_Tiffy_' WHERE a.user_gender = 1 AND a.vote...
  3. MySQL rank of a row within a sorted select statement
    I have a table of usernames, and how many times they have been voted for like this UserID, Username, Votes Using PHP I want to display a list of users sorted by votes so I use $Query = "SELECT * from Users ORDER BY 'Votes' DESC" What I want to do is output the RAN...
  4. Ranking / Sorting rows in SQL by votes and catagories A…
    Hey guys, Im using MySQL with ASP.NET/VB I have a Table which hold an PictureId as well as a votes coloum and a catagorie id. The votes col stores then number of votes a picture has (its updated everytime someone votes) For example: Pictureid Votes CatId 1 ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Raynard7Posted on 2007-06-22 at 00:03:07ID: 19339434

Hi,

unfortunatley there is no ranking function in mysql

You could do

select yt.Pictureid, yt.votes, (select count(*) from yourTable as yt1 where yt1.Votes > yt.votes) + 1 from yourTable as yt

which would give you its position by basing the number of entries that have more votes than it - and derive the rank

I'd suggest it would run faster just to pull back in order and then rank them yourself

 

by: fedders_worldPosted on 2007-06-22 at 00:19:09ID: 19339491

The example you gave
Would it use alot of cyles to calculate the rank? If say there were 100k rows?

 

by: leannonnPosted on 2007-06-22 at 02:21:00ID: 19339870

I don't mean to interrupt, but...

> Would it use alot of cyles to calculate the rank? If say there were 100k rows?

Yes it certainly would, as for each `PictureId` a ranking query is executed. This is extremely demanding on resources.

As Raynard7 suggested, it would be far better and faster to calculate the rank in your script.

 

by: fedders_worldPosted on 2007-06-22 at 04:38:16ID: 19340415

Hi thanks leannonn.
How would you suggest i script that?

Thanks :)
Feds

 

by: leannonnPosted on 2007-06-22 at 06:00:14ID: 19340843

> How would you suggest i script that?

Depends on exactly what you're trying to do.

If you're displaying a sequential list of pictures then use one query to get the picture list _without_ the rank and a separate query to get the rank just for the first item and manually increment the value in the script for all the items in your list. Same method if you're displaying info for a single picture.

 

by: fedders_worldPosted on 2007-06-22 at 08:01:46ID: 19341983

Thanks,

I'll explain what im trying to achive. We have pictures which are  tagged and people can vote on.
I want to be able to display their rank on a search results page...as in how popular they are.
So even if a search result only returns 4 results...i would also like to work out their rank based on the number of votes they have...compared to EVERY other picture in the list (the actul pictures are stored eles where but the vote count and picture id are kep in the table i mentioned in my question)

Would it make senes to use the query :
select yt.Pictureid, yt.votes, (select count(*) from yourTable as yt1 where yt1.Votes > yt.votes) + 1 from yourTable as yt

But only do it say once every half hour and store them in a rank table with a coresponding picture id.
Almost like chacehing it?

Feds

 

by: leannonnPosted on 2007-06-22 at 12:43:59ID: 19344313

Yes, that would work. You would still have to make sure the correct indexes are in place and are being used. You'll need every bit of speed with 100k rows...

 

by: fedders_worldPosted on 2007-06-22 at 20:40:45ID: 19346322

Would it be even faster to rank the votes by 'oder by votes DESC' and work out its position based on that?

 

by: leannonnPosted on 2007-06-22 at 23:06:14ID: 19346688

> Would it be even faster to rank the votes by 'oder by votes DESC' and work out its position based on that?

You mean for the half-hour query which updates all the 100k rows? You could try something like this:
---
CREATE TABLE ranksTable(
  pictureID integer NOT NULL primary key,
  rank integer NOT NULL
)
SELECT
  yT.pictureID,
  @r:=@r+1
FROM
  yourTable yt
ORDER BY
  ytvotes DESC
---

This should also be as quick as it can be for your table size.

 

by: fedders_worldPosted on 2007-06-23 at 20:38:26ID: 19349807

Thanks!!
But i do have a few question about that.
Some people upload items all the time (hence how i have 100k rows already(this is a uni internal website)

1) By running that script every half hour how do i deal with images that are uploaded and voted on in the mean time...or should i just set their rank to N/A untill the next time the script is run
2) Will this script override the previous table called rankstable...everytime...or do i need to change the name or? ( i dont want to site do crash everytime i run the script..while its doing it calulations)

But thanks so much for all your help so far! This is my first time working on a site like this/
Feds

 

by: leannonnPosted on 2007-06-24 at 00:34:30ID: 19350201

> 1) By running that script every half hour how do i deal with images that are uploaded and voted on
> in the mean time...or should i just set their rank to N/A untill the next time the script is run

Yes, you could do that as the delay should be acceptable. You can display the accurate `votes` data at any time and the `rank` is updated periodically. You can also measure the execution time of the CREATE TABLE query and if it executes fast, you can always reduce the interval (15min, 10min...)

> 2) Will this script override the previous table called rankstable...everytime...or do i need to change
>  the name or? ( i dont want to site do crash everytime i run the script..while its doing it calulations)

You can create the table manually the first time:
---
CREATE TABLE ranksTable(
  pictureID integer NOT NULL primary key,
  rank integer NOT NULL
);
---

Then on each run you can execute this:
---
REPLACE INTO ranksTable(pictureID, rank)
SELECT
  yT.pictureID,
  @r:=@r+1
FROM
  yourTable yt
ORDER BY
  ytvotes DESC
---

This will update the old data and insert any new data (for newly uploaded pictures).

 

by: fedders_worldPosted on 2007-06-24 at 03:01:31ID: 19350446

Hey Leannon.
I am doing what you suggested, but im getting the error:
Data truncated for column 'rank' at row 1

This is the code: (with my table and cols in it)

REPLACE INTO ranksTable(pictureID, rank)
SELECT
  yT.PicId,
  @r:=@r+1
FROM
  picture_count yt
ORDER BY
  yt.VoteCount DESC

-----------------------------------------

 

by: leannonnPosted on 2007-06-24 at 03:14:39ID: 19350474

Try issuing the commands in this order. The variable does not reset in the same session:
---
SET @r:=0;

REPLACE INTO ranksTable(pictureID, rank)
SELECT
  yT.PicId,
  @r:=@r+1
FROM
  picture_count yt
ORDER BY
  yt.VoteCount DESC;
---

 

by: fedders_worldPosted on 2007-06-24 at 03:37:06ID: 19350529

:(
I'm still getting the same error. Im sure im doing something wrong but i dont know what.
I copied and pasted
SET @r:=0;

REPLACE INTO ranksTable(pictureID, rank)
SELECT
  yT.PicId,
  @r:=@r+1
FROM
  picture_count yt
ORDER BY
  yt.VoteCount DESC;

Into MySql Query Browser and im getting the same error :(

Thanks for your help
Feds

 

by: leannonnPosted on 2007-06-24 at 04:03:39ID: 19350594

Then you are having a slightly different problem. Try this instead (no SET this time):
---
REPLACE INTO ranksTable(pictureID, rank)
SELECT
  yT.PicId,
  @r:=@r+1 as rank
FROM
  (SELECT @r:=0) r, picture_count yt
ORDER BY
  yt.VoteCount DESC;
---

Is there still an error?

 

by: fedders_worldPosted on 2007-06-24 at 04:36:00ID: 19350687

WONDERFUL!!!
So this only will update rows that need changing...like new itmes etc.
This works really well..thanks so much
Feds

 

by: fedders_worldPosted on 2007-06-24 at 04:38:22ID: 19350692

Oh just one question...how long would it take..or the amount of resrouces with the 100k pic...i know it depends on the actul server and what eles its doing...but what would you consider reasonable

 

by: leannonnPosted on 2007-06-24 at 04:50:51ID: 19350732

This should be very, very fast - below 2 seconds.This is from my test tables:
---
mysql> SELECT count(*) FROM picture_count;
+----------+
| count(*) |
+----------+
|   101024 |
+----------+
1 row in set (0.00 sec)

mysql> REPLACE INTO ranksTable(pictureID, rank)
    -> SELECT
    ->   yT.PicId,
    ->   @r:=@r+1 as rank
    -> FROM
    ->   (SELECT @r:=0) r, picture_count yt
    -> ORDER BY
    ->   yt.VoteCount DESC;
Query OK, 202048 rows affected (1.83 sec)
Records: 101024  Duplicates: 101024  Warnings: 0
---

 

by: fedders_worldPosted on 2007-06-24 at 05:09:17ID: 19350783

Thanks you really have helped :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...