Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Ranking System: Retrieving Results Around Your Rank


I'm building a ranking system for a game. I'm trying to determine the best way to select a players rank, and then display the records around that players ranking.

For instance:

Username | Rank
steve | 6000
bob | 5000
jane | 4000
chris | 3000
brian | 2000
tim | 1000
molly | 0

Assuming chris is the current player, I want to select his rank, and then run a query that returns the two players ranked higher than him, and the two players ranked lower than him. So the query would return the following:


bob | 5000
jane | 4000
chris | 3000 //I'd rather leave his own rank out.. but it's not bad like this.
brian | 2000
tim | 1000

What I can't figure out how to do, is determine the row that is specific to Chris's rank. I would need to define a starting point (-2 rows from Chris), and an end point (+2 rows from Chris), order by and limit the results... what I can't figure out though, is how to get the specific row number to start from.

For instance, lets say Chris is row 583 of my database... how do I retrieve that number?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Retrieving Rank Of Player After Order By DESC
I'm new to MySQL but I do have some knowledge of SQL. I need some advice regarding writing retrieving statement.

My objective: I want to retrieve the rank of a player according to his score. All ranks are calculated base on their scores, where higher rank means lower score. Code:

Ranking System
I've made a forum and i want to have a ranking system with it. I managed to display a postcount but i also want a few images to be displayed, like if you have made more then 50 posts, it displays 50.jpg or something, how can i accomplish this, in another way then just str_replace()ing all the number of posts?
And how do i display 2, like if you have 50 posts, 50.jpg and if you have 60 posts, 60.jpg.

Scoreboard Ranking System
I have created a high score table that will potentially store > 10000 user scores, and need to determine ranking for items pulled out. Ther have been posts detailing how to do this when selecting ALL records, but in my case, I need to pull out specific rows, and determine their rank against the entire table.
For instance, a user gets a high score that would rank them at #1200, I need to pull out their score, as well as the 3 above and 3 below. I accomplished this by storing the insert_id, and selecting rows where the score is above and below (in seperate queries), but this makes it quite impossible to get a rank.
An alternative method is having a rank column and updating it every time a new score is added, but if it cant be done in one query, it would be a very inefficient method.
Does anyone have any solutions on how to approach this? I am using mysql 3.23, so I dont have use of sub-queries.

Ranking Results
Im trying to display baseball team stats, along with the ranking for that particular league.
for example, there are 5 teams in the league, Team A has 12 HR, B has 15 HR, C has 3 HR, D has 3, and E has 20.
I want to show on each individual team page their stat, with the rtanking for the league.

Retrieving Top 100 Results
I am trying to get an average value from my database but I only want to retrieve the average out of the top 100 results. The column I want to average contains values from 0.1 to 10.0.

So I want to get the average from the top 100 values in this column. The average syntax is clear but what do I have to add?

This is what I have now:

$query="select AVG(M_RATING) as rating FROM rate_members WHERE M_COUNTRY='SE'";
But this gives me an average based on all values in the column.

SQL Rank Problem
right i have a table data_9(domain,title,url,text)

basically i want an sql statement to rank in desc order the group of domains. pretty easy but i also want to rank in desc order the group of urls and merge this with domains.

basically i want the top ranking domains to be displayed and the title, url and text is the top result from the top ranking domain url group.

possible?

Getting Rank From A Table
I have a table with (id, score) and im trying to write a query that will return the rank of a certain id ranked by order of score.eg. highest score would return a rank of 1.

i got this far;

SET @i = 0;
SELECT id, @i:=@i+1 AS rank
FROM scores
ORDER BY score DESC;

which returns a table of ranks which is correct but then i need to select just one of those rows specified by an id. I tried some kind of subquery but it didnt seem to work.

Order Two Tables By Rank
I've got a table called "jingles". Jingles can contain "individual cuts". These individual cuts can be sorted into groups as well, so the order will be:

Jingle => IndividualCutGroup => IndividualCut
,or Jingle => IndividualCut

I store the individual cuts in a table called "individual_cuts", which has both a group_id (which is used when the cut belongs to a group) and a jingles_id (which is used when the cut belongs directly to a jingle).
Both tables contain a "rank" field by which I'd like to order.

How can I order by rank when the data is spread over two tables? Also, individual cuts containing a group_id should be ordered by rank within that particular group.

Selecting Rank Over Time
I have 4 colums in my table.. they are id(int), usrid (int), datestamp (date) and credits(float).

here's what i'd like to do.. select the numeric rank of a given userid over the past 30 days based on the most credits... ideally i'd like it all to be in one query but that may not be possible.. any ideas are welcome here, i'm stumped on this one.. so far all i've been able to do is select all the entries from the last 30 days..

SELECT *
FROM daycredit
WHERE TO_DAYS( NOW( ) ) - TO_DAYS( datestamp ) <= 30
and usrid = $usrid LIMIT 0, 30

Creating A Rank Column For Query
My problem is how do I create a rank column for a query. Meaning depending on a students score they will have a rank of 4 for example. Also if two students ahve the same score there rank should be the same and the next students rank would be 2 more. I tried using a global variable but dont know how to increment it properly. There must be an easier way of doin this then Im thinking of.....

How To Get Sort Index (Rank) Without Returning All Prior Records?
I want to get the sorted rank of a record without returning all prior records and counting them. Is it possible to get the order index given a unique key value, or even using the unique value of a field within any SELECT statement?

For example:
100,000 players in a network game.
Player ID is unqiue and scores are indexed.
Specific player asks for his rank among the scores of the 100,000 players.
Return rank of the record without returning all records up to player's record.
Returning player's specific record with the rank would be a plus.

Ranking Scores
I need to create a query that will sort a bunch of scores in ascending order and then add a column with their rank code from 1 to however many is in the table.
the link below shows an example image of what i need to happen.

A Ranking Leaderboard
I am trying to design and implement an online leaderboard in MySQL and PHP.  Maybe it is because of lack experience in this field but I am really confused on the basics on how this could be achieved.

Correct me if I'm wrong but data is not stored in any order as such in a SQL db.  It is the query you write/code which does the sorting.  How then is it possible to have a leaderboard with rankings on?

For example if I had a basic table with fields of name and points.

You could write a basic query to display the top 10 (or whatever limit you choose) users by points, ascending or desc, etc.  However if you then have a leaderboard with thousands of users on a leaderboard, this wouldn't be practical.  You could obviously pull an individuals record up by using WHERE and the name.

How would I get SQL to output the users ranking?  Surely I cannot do it with an extra field called ranking as everytime the ranking changed ALL records would need to be updated...

Surely this kind of thing has been done before.  I just can't imagine doing this with SQL due to the nature data is stored and then later sorted.

Ranking MySQL
I have a query that extracts the last 7 records from a database based on its criteria and have it ordered by its date. What i want to do is add a column in the select statement and put in the numbers from 1 to 7 into the column in this added column.

I'm using the Space(1) as Number function but i am wondering how do I put 1 to 7 in the table. Its pretty much like a ranking system.

Ranking Users
i'm trying to rank the users in our site.
table contains:
- userid
- userrates
and with thousands of records.
member with the highest rate goes #1, next is #2 and so on.
i want the query to be like:
Code:
<something goes here> WHERE userid = '$userid' order by userrates desc
from the code above it will show the rank of this user.
then the next user logsin and it shows again his/her ranking.
hope someone understands this
any input is appreaciated

Ranking Leaderboard In MySQL!?
I am trying to design and implement an online leaderboard in MySQL and PHP. Maybe it is because of lack experience in this field but I am really confused on the basics on how this could be achieved.

Correct me if I'm wrong but data is not stored in any order as such in a SQL db. It is the query you write/code which does the sorting. How then is it possible to have a leaderboard with rankings on?

For example if I had a basic table with fields of name and points.

You could write a basic query to display the top 10 (or whatever limit you choose) users by points, ascending or desc, etc. However if you then have a leaderboard with thousands of users on a leaderboard, this wouldn't be practical. You could obviously pull an individuals record up by using WHERE and the name.

How would I get SQL to output the users ranking? Surely I cannot do it with an extra field called ranking as everytime the ranking changed ALL records would need to be updated...

Surely this kind of thing has been done before. I just can't imagine doing this with SQL due to the nature data is stored and then later sorted.

Ranking Query (self Join)
I would like to get a rank (row # of ordered results) of an article based on its average rating in relation to all other articles. I have a ratings table that holds all of the individual votes cast by users (ratingID, articleID, userID, rating). So I need to order the articles by AVG(ratings.rating) and then come up with an individual article's row # to find its ranking.

I know this involves joining the ratings table on itself with a greater than or less than operator, but i'm completely lost when it comes to self-joins. I know this is easy, but there is a small trick to it and i'm clueless.

Ranking For Multiple Columns
A query in my application return several columns with amounts, Now i need to add a ranking to all those columns seperatly.

So the result should be something like this:

ID     Amount1  Ranking1  Amount2 Ranking2
----   -------- --------- ------- --------
135     123.34      4       23.00     3
184     160.23      1       60.89     2
845     140.22      3      100.20     1
987     155.00      2        1.20     4

The ID isnt important here.

The only solution i can think of now is to create a (temp) table, populate it with the query, and then sort it for each ranking and fill the ranking one by one.

Is there a way to get the ranking filled in  the same pass as the amounts are calculated?

Sort And Give Ranking
let say i've have these following table.

tblA
name | marks
-----------------
robert | 39
johnny | 78
bruce | 23
elena | 56
halim | 23

formula, if same marks (see bruce and halim), sort them by name
how to query? expected output showing as below:

no | name | marks
----------------------------
1 | johnny | 78
2 | elena | 56
3 | robert | 39
4 | bruce | 23
5 | halim | 23

Sorting And Put Ranking In Field
I have 3 field in my table Ranking, Name and Score. Is it possible to sort all record to order by Score and put Ranking no. to each record by using query not much?

Ranking Student Grade? With Subquery/subselect?
I am a mySQL newbie here and have some problem defining the mySQL 4.0.14
or 3.23 SQL to get student grade ranking where tied grade have the same
rank.

I used to set it through MS Access 2002 and use this kind of query:

SELECT nilai.studentNIS, nilai.studenttestmark,
(SELECT COUNT(*) FROM tblStudentGrades
WHERE [studenttestmark]>[Nilai].[studenttestmark];)+1 AS NomorUrut FROM
tblStudentGrades AS nilai ORDER BY nilai.studenttestmark DESC;

I've been looking around mySQL documentation and read that subquery can
be redefined as INNER JOIN or using two SQL statement via variable? I
have no idea on the basics of how to set it out though.

Could one of you please help give a me a sample on how this kind of
query should be done on mySQL? Is it possible to do it in single line?
And without having to use PHP/Perl scripts?

Or maybe I should have approach it differently?

Full-Text Search: Truncation Operator And Relevance Ranking?
We would like to begin supporting the truncation operator on our website's search engine--however, we still require the results to be sorted by relevance. If a client enters "televis*" into the search engine, and we perform the search in boolean mode, pages containing "television", "televise", "televised", etc will be returned. However, because it is a boolean mode search, all rows will have a relevancy value of 1.

A user-provided "workaround" on the MySQL site said to use the same keywords but NOT in boolean mode to get a usable relevance ranking. However, a standard fulltext search for "televis" or "televis*" will return no rows.

Retrieving MAX(col)
I have a query that returns 25 rows. How would I get the MAX value of a column from this query? I don't want to group the results because then my query will get grouped and I don't want that.

Random Retrieving
data in myTable

(id) name
(1) Tom
(4) Jane
(8) John
I have data in myTable like the above.

Can I retrieve one of names in name column randomly?

Retrieving Pictures
im in the process of adding path a name of a picture into a field so that i see it in my web browser. it isnt working! ive got car_make and images fields. the image field is varchar. is this correct?

basically need these pictures to upload into my browser but im struggling to insert paths into the database in the first place. any help is appreciated. thanks

p.s. when i change the field type to BLOB in phpmyadmin it says binary, do not edit. it wont let me edit the field any more.

Retrieving LAST_INSERT_ID
"SELECT LAST_INSERT_ID()" returns the last inserted value of an AUTO_INCREMENT column.
But can only be used after an insert (as far as i know).
What should i do to retrieve this value from a specific table?

I've tried:
SELECT LAST_INSERT_ID(table.column)
SELECT LAST_INSERT_ID(table)
SELECT LAST_INSERT_ID(column)

...but didnt work. I dont know if MySQL doesnt support these statements or if the version im using is old (4.0.15). Ill upgrade as soon as i get the time to download the newest version (35mb)

Retrieving From 2 Tables
I have 2 tables, Male and Female.

Male has a field guyName and contains: ['John', 'Jack'].
Female has a field girlName and contains: ['Mary,'Emily'].

What query should I use to get an array like this:

[[0]=>Array(guyName=>'John'),[1]=>Array(guyName=>'Jack'),
[2]=>Array(girlName=>'Mary'), [3]=>Array(girlName=>'Emily')]?

I used
SELECT guyName FROM Male UNION SELECT girlName FROM Female and I get this:

Array ( [0] => Array ( [guyName] => John) [1] => Array ( [guyName] => Jack ) [2] => Array ( [guyName] => Mary ) [3] => Array ( [guyName] => Emily ) )

I want the key to match with the table field correctly.

Retrieving Data
i am having 3 tables in my db.how can i display all d product ids in "tbprod" table that are under a category id which is in d `tbcat` as `catid`.

CREATE TABLE `tbcat` (
`catid` int(10) unsigned NOT NULL auto_increment
}

CREATE TABLE `tbsubcat` (
`scatid` int(10) unsigned NOT NULL auto_increment,
`catid` int(10) unsigned NOT NULL default '0'
}

CREATE TABLE `tbprod` (
`pdid` int(10) unsigned NOT NULL auto_increment,
`scatid` int(10) unsigned NOT NULL default '0'
}

Retrieving Values From Url
i want to put the value in a variable but dont know how to retrieve it:

i want to use record_num = 3 as a variable:

URL: .../review.php?,record_num=3

EXAMPLE OF VAR

$link_id ='[record_num]';

SOURCE
<a href='review.php?,record_num={$row['link_id']}'>LINK</a>

Retrieving Information As It Is
I have a mulitline input field, going to a database, when i view the inputted information in the database "browse" i looks exactly like it does when i typed it in for example

Line one
Line Two

When i get the information back out using a SQL statement it come out in one lone line thus Line one Line two, with two boxes in between where the line break should be.

I need to to come out as it went in

Is this possible?

Retrieving News
[I]I am doing on my final year project. One part is mySql. how come my client's application ( Java) retrieve news from my data base. Cos i faced some problems linking the codes to the time stamp of the data base.

Retrieving New Record ID
I'm making a web-site thats backended by php-2-mysql. A common problem seems
to be when processing form data, I use information early in the form to
create a new record in a main table. I then immediately need the
auto_incremented Key-ID of the new record to put other information in
related tables.

In the past i've gotten that ID by just doing a SELECT with a WHERE that
matches all the values i've just INSERTED, but it seems a cumbersome
method.

Retrieving New Record ID
I'm making a web-site thats backended by php-2-mysql. A common problem seems
to be when processing form data, I use information early in the form to
create a new record in a main table. I then immediately need the
auto_incremented Key-ID of the new record to put other information in
related tables.

In the past i've gotten that ID by just doing a SELECT with a WHERE that
matches all the values i've just INSERTED, but it seems a cumbersome
method.

Retrieving Records
hi,
I have the following table:

ID Type TimeStampe

10 1 2005-04-25 16:37:58
10 2 2005-04-25 16:39:58
10 3 2005-04-25 16:38:58
10 4 2005-04-25 16:38:58

I need to create a query that will get me 2 types (limit 2) that have the oldest timestamp (1 and 3).

Retrieving All Records
I have a table with a field called "posted" that contains a UNIX timestamp of the time it was posted. I would like to set up a query to get all of the posts that occurred for the current month. What I have is..
Code:
SELECT * FROM posts WHERE FROM_UNIXTIME(posted,%m) = DATE_FORMAT(NOW(),%m)

Is this correct, or is there a more optimized way to do it?

Retrieving First Sentence
Does anyone know how I can extract the first sentence from a text field? I've got it right up to a point with SUBSTRING_INDEX but it's not quite good enough. The problem is that I want to stop capturing the substring at the first occurence of one of three possible characters: ! . ?

SUBSTRING_INDEX doesn't seem to allow multiple delimiter characters so I guess I'm looking at regexp but I'm not sure how to go about it. Here's my current query:


Code:


SELECT SUBSTRING_INDEX(item, '.', 1) AS preview FROM entries;

Retrieving Data
Came to ask you gurus to help me out with the below error:
1064 - You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'on o.blacklisted = c.blacklisted where c.customers_id = '0' , o

select count(*) as total from orders o left join orders_total ot on (o.orders_id = ot.orders_id), customers c on o.blacklisted = c.blacklisted where c.customers_id = '0' , orders_status s where o.orders_status = s.orders_status_id and s.language_id = '1' and ot.class = 'ot_total'

Since I could not understand very well where I made mistake, I like to ask you guys to help me. If the above error does not give you a right picture, I can post the php codes where from this error came.

Retrieving Unicode Data
I have an existing JSP web application which retrieved data from a
SQLServer database and displayed it. The data contained Unicode chars. This
worked fine. I changed databases/JDBC drivers over to MySQL. I've set the
database to use utf8 and the tables as well. I've viewed the data in the
table and it contains unicode just fine, however, the query returns data
with all the unicode chars converted to question marks. I have searched for
a solution to this for hours and no luck so far.

I've tried passing in useUnicode=true and characterEncoding=UTF8 in the URL
connection string and this has done nothing. Then I read that by default
the driver has the useUnicode set to true. I tried setting it to false to
see if it would do anything. Nothing. Code:

Retrieving Last Auto-increment
I've got a project where I'm adding records to a database, and the primary key is autogenerated (pretty standard). What I want to do is retrieve the id of the last record added to the database, so I can use it in another part of the script.

I'm currently using a select statement, but there has to be a way of doing it without another query.

Retrieving Data Through A Form.
I'm setting up a database and I want to retrieve data from the db through a form.

I currently have:

$sql = "SELECT * FROM Tasks WHERE t_id = '$_POST[t_id]'";

$result = mysql_query($sql, $conn) or die(mysql_error());

while ($newArray = mysql_fetch_array($result)){
$id = $newArray['t_id'];

echo "ID: $id <br>";

I don't think that the 'WHERE t_id = '$_POST...' part is correct, as the code seems to do what it is supposed to when I take that part out, it just doesn't do what I want it to do.

So.. to clarify; I insert a task id (t_id) into the form, hit the submit button, and it is supposed to show the results (echo "ID: $id <br>";). I hope this makes sense to someone. Code:

RETRIEVING DATA FROM FOUR TABLES
I need to retrieve data from four tables into one php "$result" with one MySQL query.  The tables are configured as follows:

Images
   ImageID (primary key & the only unique field)
   Serial
   Photographer (all photographers are listed once in the Posters.Photographer field, ie many to one)
   Operator     (only some operators are listed in the Operators.Operator field, not all, ie many to the occasional one)
   Subject (all subjects are listed once in the Subject.Subject field, ie many to one)

Operators
   Operator (primary key)   
   OpField1
   OpField2
   etc

Photographers
   Photographer  (primary key)
   PhoField1
   PhoField2
   etc

Subjects
   Subjects      (primary key)
   SubField1
   SubField2
   etc

The task:  I need to select ALL images from the Images table meeting criteria set by conditionals on fields in that table, eg 'where Serial = "ABCDE"'.  For each hit I need to fetch all the relevant fields from all four tables, relating to the Image, the Operator (where they exist), Photographer and Subject. Obviously I don't need to retrieve the linking fields twice.

"The answer's going to be a left join" I hear you thinking - well, something like that.  Because a straight join between Images.Operator and Operators.Operator results in the correct image data not being retrieved when the particular operator does not appear in the Operators table (there are good reasons for this, the details for many operators simply don't exist or can't be traced).

So, either I add all the Operators that occur in the Images table to the Operators table, even though there is nothing to put in the detail fields, or I need a query that successfully combines all the correct kinds of joins.  I've found a few likely-looking examples to follow on the internet and in books, but all sorts of unexpected things happened when I tried them.  I've read so much about joins that my head's ing.  And I don't learn so fast these days (no hair left to keep the few remaining brain cells warmed up).  I have a suspicion that it's actually less complicated than the guidance makes it out to be...

Retrieving Order Number
is there a way to retrieve the order number along with the other fields in a select statement ?

for example if I have a query that selects the following results:

ID Value
-----------
1 1345
3 8275
5 2384
7 2345

I want a way to retrieve the following results:

Recno ID Value
--------------------
1 1 1345
2 3 8275
3 5 2384
4 7 2345

Retrieving User Password?
I created a mysql DB and I can't recall the password that I used for the main user. Something has come up and I need to retrieve the PW I created for the user, is this possible?

If so, how do I do this from cpanel?

Retrieving Mysql Into Web Table
OK, I’m trying to simply retrieve records from a table in Mysql. Say I have around 60 to 110 rows in a table of different members each with a (FirstName, LastName and Contact) field, and I would like to show them all on a web page.

As it is the first time I’m trying myself with table in PhP my question is, am I’m doing it right ??? Do I use the markers around the <br>, <div> and other tags in the right way ???

My code I have shown below includes several different code’s which looked to me promising, well if somebody could help here so I can actually retrieve information from a specific table. Code:

Retrieving The Last Value Of A Specific Column
I need help in retrieving the last value that is entered in my table for a specific column

An example to clarify what I want to do:

I am collecting data automatically and the values of which are being inserted into a database. I want to retrieve for example the last row entered for a column named e.g. current_number. I am not sure how this can be done in SQL.

One idea I had is to use the last_insert_id(), but I am not so sure how to use it as an sql query. Is there another way to get the the last value of a specific column in a table?


Retrieving Last Inserted Record
After a use the INSERT command to enter something into the database I seem to remember a way to get the record that was just created using some kind of SELECT command. I seem to remember "SELECT @" or something similiar.

how I can go about getting the record just inserted with the INSERT command?

Retrieving Information From MySQL
I have created a an online shop and it works fine on localhost and on the test server, however we want to intregate it with an online bank and its not working properly.

When purchasing a single product the product can be purchased successfully however multiple products cannot purchased successfully.

For some reason the page on the online banks server cannot access one our database that stores the information in the customers shopping cart but it can retrieve the information for a single product order. Im not sure if its some kind of issue on there server?

SQL For Retrieving 10 Highest Values
So basically I need the SQL query that retrieves from a table 'users' the 10 highest values from the field 'points'.

Retrieving Dates In SELECT
Im trying to select some results from a query and use a WHERE clause to extract ones that were only created greater than July 1st 2007.

In the table, there is a 'created' column which stores a unix timestamp. The sql im using is

"SELECT post,created FROM table1 WHERE created >= 1183348800"

It seems that the WHERE clause is just comparing the acutal number and not realizing that it is a unix date.Is there a function that I am able to use?


Copyright © 2005-08 www.BigResource.com, All rights reserved