473,756 Members | 9,662 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rank by 2 columns in mysql

15 New Member
Hi All,

I'll try and explain as best as possible what I'm trying to do and hopefully someone can tell me the best way to do it!

I'm basically trying to rank by 2 columns in mysql/php, by this i mean i have a column called `Turnover` and one of `Cash` I would like to display each column in a table with its ranking in the column to the right.

So far i have:

Expand|Select|Wrap|Line Numbers
  1. include ("database.php");
  2. global $conn;
  3.  
  4. mysql_query("set @rankA=0;"); 
  5. $sql = "
  6.     SELECT `name`, `id`, `year`, `Turnover`, `Cash`, @rankA:=@rankA+1 AS rankA 
  7.     FROM stocks
  8.     LEFT JOIN data ON `id` = `company_id` 
  9.     WHERE     `year` = '2007' AND
  10.             `Turnover` IS NOT NULL AND
  11.             `Turnover` != 0
  12.     ORDER BY Turnover DESC
  13. ;";
  14.  
  15.     $result = mysql_query($sql);
  16.     echo mysql_num_rows($result)."<br />";
  17.     echo $sql."<br />";
  18.     echo "<table width=200 border=1>\n";
  19.     while($row = mysql_fetch_assoc($result)) {
  20.         echo "<tr>\n";
  21.         echo "\t<td>".$row['id']."</td>\n";
  22.         echo "\t<td>".$row['name']."</td>\n";
  23.         echo "\t<td>".$row['year']."</td>\n";
  24.         echo "\t<td>".$row['Turnover']."</td>\n";
  25.         echo "\t<td>".$row['rankA']."</td>\n";
  26.         echo "\t<td>".$row['Cash']."</td>\n";
  27.         echo "</tr>\n";
  28.     }
  29.     echo "</table>\n";
  30.     mysql_close($link);
  31.  
Now obviously this works very well and shows me the data ordered by Turnover with rankA in the column to the right, but what i really want to add next is to have another column with the value of the data ordered by Cash (rankB). But i of course want to keep rankA as well.

I'm not new to mysql but i'm fully aware that i don't know how to use it to its greatest potential. The only solution that i have at the moment is to have a whole seperate php function which computes rank for Turnover, and stores it in the table, then computes rank for Cash and stores that in the table too. Now with the amount of data i have this is really not an option, plus the data is frequently updated so the function would have to be rerun every time.

I'm thinking there must be a way to run the query ordered by Turnover and then somehow carry rankA through for when i run it again ordered by Cash, setting RankB; then display the whole lot, but i simply don't know how.

Any suggestions would be much appreciated.

Thanks

Andy
Mar 4 '09 #1
6 5644
chaarmann
785 Recognized Expert Contributor
Why don't you just get the data unsorted from the database and store them in an array? Then to get the data sorted the one or the other way is just a single command in PHP that sorts the whole array by the column given.

It is generally a bad idea to put a lot of load on the database to let it sort the records. You are slowing down every other application that also needs data from the database. If you sort it yourself, you only make your own process slower but don't affect others.
Mar 6 '09 #2
vegetable21
15 New Member
Ah I c, that would explain a lot! many thanks for pointing that out!

However I now have another problem in that I can't sort the array in php properly.
Expand|Select|Wrap|Line Numbers
  1. bool array_multisort ( array $arr [, mixed $arg [, mixed $... ]] )
For Example:
Expand|Select|Wrap|Line Numbers
  1. $sql = "SELECT `name`, `company_id`, `year`, `Turnover` FROM `data` WHERE `year` = '2007';";
  2. $result = mysql_query($sql, $conn);
  3. if (!$result) { die("Invalid query: " . mysql_error()); }
  4. $arr = array();
  5. while($row = mysql_fetch_assoc($result)) {
  6.     $arr[] = $row;
  7. }
  8. array_multisort($arr['Turnover'], SORT_NUMERIC, SORT_DESC);
  9.  
Surely the above is sorting each $row array within $arr rather than sorting by $arr['Turnover'] within the whole $arr?

I've read http://uk.php.net/array_multisort and the w3schools pages on array sort but I'm still not getting it,

And help would be much appreciated.
Mar 6 '09 #3
wizardry
201 New Member
you could use order by for multiple columns and adjust the where clause for that fields.

Usually your sla will have more designated cpu time for your database then app. or equally spread just depends.

but you could have the right sla where you dont need to worry about over head.

either way its better to have the database do the work from a dba point of view.
Mar 6 '09 #4
vegetable21
15 New Member
wizardry, that's what I had originally thought that it would be better to let the database do the ranking but then the time delay started creeping in.

I think I would like to know how to implement both solutions that wizardry and chaarmann have eluded to,

1) if someone could advise me the correct way to implement the array sort using my example in my last post, I would be eternally grateful.

&

2) if someone could show me how order by multiple columns then that would be great too, but please see my original post and note that I simply don't want to order by one then the other. I have no idea if this is possible, but wizardry is suggesting it is.
Mar 6 '09 #5
chaarmann
785 Recognized Expert Contributor
@vegetable21
I never used arrays in php before, but it seems to be not logical to me how you try to sort it . All sort functions I have seen so far, no matter what language, need an index and the array itself. But $arr['Turnover'] only gives you the index, so where is the array itself in your argument list that you pass to your sort function ???
I googled an found this:
static function multi2dSortAsc( &$arr, $key){
$sort_col = array();
foreach ($arr as $sub) $sort_col[] = $sub[$key];
array_multisort ($sort_col, $arr);
}
The crux is that we have to create the 1D array we want to sort by on the fly, once we have this array it can be used to sort the parent 2D array by passing it as a second argument.
As I said, I am a newbie in php, but how I understand it is that you did not pass the array as second argument. Just add it in your original code:
Expand|Select|Wrap|Line Numbers
  1. array_multisort($arr['Turnover'], $arr, SORT_NUMERIC, SORT_DESC); 
I have no possibility to run PHP code myself, so if that doesn't work, then you should ask this question about sorting in the PHP forum again.

If you need the array sorted by different columns (I assume you have a column name in your GUI or webpage that you can click or select to sort it), then get it unsorted from database, buffer it and sort it in php. In this case you only access the database once and get the data, no matter how often the user wants it to sort. That's a huge performance gain than doing the opposite: get it again and again from database everytime the user clicks on a column to sort it.
And what about different character sets and collations your DB uses while sorting? How does your database suport that? I guess with proprietary SQL-syntax only. And if you change the database? Then you need to rewrite all your SQLs! In opposite to that the php-code for sorting an array always stays the same.

Sorting by php puts load on the webserver, sorting by DB puts load on the database server. What if you run into performance problems? Then in most cases it's much easier to just add a new webserver than to add a new database server and do all the required data synchronization s between both DB-servers.

Anyway, there is only one situation where you should let the database sort the results:
If for example the query returns million of records, but you only need the first 10 of them (SQL-command "limit"). Then it's a lot of faster that way. But in your query provided you don't use.
if you still want to let the database sort it then you could just modify the "ORDER BY Turnover DESC" clause in your SQL-query by replacing "Turnover" with the column name you want to sort by.
Mar 9 '09 #6
vegetable21
15 New Member
thanks chaarmann, i found that link not long after i posted the last response.

i have now got it doing exactly what i want using the array_multisort (), the documentation on php.net is pretty rubbish on this but yes you are right you need an index to sort the array against. it's still quite slow, but not half as slow when i was getting SQL to do the sorting, and when i consider the amount i'm trying to make it do its pretty fast.

many thanks for all contributions!
Mar 9 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1254
by: Wakan | last post by:
HI, is there a way to obtain only the affected columns after an update query? After an update query, that involves 10 columns, I know that only 2 columns are really updated (because the values of the other cols don't change). I need to know the names of that changed cols, for logging purpose. Someone can help me? Thanks
6
6580
by: Junkmail | last post by:
I have an application with highly compressable strings (gzip encoding usually does somewhere between 20-50X reduction.) My base 350MB database is mostly made up of these slowly (or even static) strings. I would like to compress these so that my disk I/O and memory footprint is greatly reduced. Some databases have the ability to provide a compressed table, compressed column, or provide a user defined function to compress an indvidual...
3
5015
by: Dave Crypto | last post by:
Hi There, SUMMARY: I need to know what the actual maximum date limit possible on a row of a MYSQL database. MORE DETAILS: For example, does a MYSQL database only allow 4032 bytes of data to be
4
1582
by: MuZZy | last post by:
Hi, I just wonder if someone can help me with this: I need to create a sql script which will run when user installs/upgrades my app. User may already have the database and tables tructure setup on the server, or may not. The script needs to conditionally create database, conditionally create tables, and conditionally add columns to the tables if needed. I could perform this on MS SQL, as the master database has all info about all...
2
1961
by: dam_fool_2003 | last post by:
Just now I asked a question about signed char and unsigned char. I had the replay very fast by jens.torring and Tim prince. I post via google so now goes my thanking replay. (I must be more precise according to jens.torring's replay) As I was reading the slandered draft C99 about the conversion (6.3) I have interpreted the word conversion rank as the range of a variable (as per defined in limits.h). Am I wrong in my understanding? (I...
3
3277
by: snowweb | last post by:
I'm creating my first web application in PHP/MySQL, however, when I go to view the database contents, the data has been stored in the wrong columns. I've gone through my insertion code with a fine toothcomb and can see no errors which might cause this. I will post the code below, and you will see that I have some diagnostics built in, which show that the information (at least at that point) appears to be about to be stored in the correct...
2
2957
by: rusmo1 | last post by:
I have a GridvVew in which all of the columns are sortable. I want the first column to display the position of the row in the sorted order regardless of which column I've sorted or which direction it is currently sorted. This "rank" column should always display like so: 1 2 3 4 5 etc...
3
2176
by: Wayne Wengert | last post by:
I have a VS2005/VB Windows application in which I want to rank the contents of a "total" field in a dataset but I can't seem to figure out how to do this. I've created an SQL DataAdapter and an SQL Dataset and I filled the dataset with the values needed. The dataset has "n" rows and the columns include "total" (a decimal value) and "rank" (an integer initially set to zero). I want to place the ranking value (e.g. 1 through n) for each value...
2
2948
by: orenlevy1 | last post by:
Hi Everyone. I have a problem that I could not figure out what to do with it. I have a couple of tables and views. All have the same unique ID. When a user try to do a search on our web site we want to try to look in multiple tables and views, Rank the results and aggregate the results back (remove any duplicates). Part of the search is a Full Text Index search. I created already the following query that seems to be working ok...
0
9292
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9901
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9878
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7282
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6551
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5322
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3827
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3392
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2694
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.