Banners
Banners

Reputation: 71

Adding a rank value to my MySQL table

I have a fixed table that will not change. I have over 80,000 rows.

CREATE TABLE `word_list_master` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `word` varchar(64) NOT NULL,
  `created` int(11) NOT NULL,
  `frequency` int(11) NOT NULL,
  `number_of_files` int(11) NOT NULL,
  `combined_frequency` bigint(24) NOT NULL,
  PRIMARY KEY (`id`)
)

I want to create a 7th column 'rank' that will determine the rank of the rows ordered by the combined_frequency column. I am doing this to reduce overhead when the database is live.

Can I do this via MySQL statement(s) or do I have to write a bunch of SELECT/INSERT statements in PHP (for example)? I have been doing most of the work so far in PHP but it is taking up to 24 hours to perform operations on the table.

I was looking at the RANK function but as my MySQL ability is only fair in capacity, I ran into problems.

Upvotes: 4

Views: 2361

Answers (2)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79919

This is how you add a rank field to your table:

 SET @rownum = 0; 

 SELECT *,  (@rownum := @rownum + 1) AS rank
 FROM word_list_master
 ORDER BY combined_frequency DESC;

Update: If you want to write queries against that rank field, you have to use the previous table as a derived table like so:

SET @rownum = 0; 
SELECT *
FROM
(
   SELECT *,  (@rownum := @rownum + 1) AS rank
   FROM word_list_master
   ORDER BY combined_frequency DESC;
) t
WHERE rank = 5

And if you want to paging your query like so:

SET @rownum = 0; 
SELECT *
FROM
(
   SELECT *,  (@rownum := @rownum + 1) AS rank
   FROM word_list_master
   ORDER BY combined_frequency DESC;
) t
WHERE rank BETWEEN ((@PageNum - 1) * @PageSize + 1)
AND (@PageNum * @PageSize)

Update:

Note that there is already a buit-in way to do this instead of this awful query which is the [LIMIT {[offset,] row_count }], which is the standard mysql-way to do this. Don't use the previous way if you just want to get a limited result set from your query.

Upvotes: 1

user229044
user229044

Reputation: 239260

Normally I wouldn't consider "don't do this" to be a valid answer to such a question, but you're not going to help your situation by adding a new column. You already have a numeric column by which to order your data. Adding a second numeric column for this purpose is not only over-kill, it is bad design.

If it's taking "up to 24 hours" to do any operation on a table containing only 80,000 rows (which is not very many) then you need to add indexes to the columns being used to search/sort/join.

Upvotes: 2

Related Questions