Compare query, how?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

Compare query, how?

Post by Czar »

How can i compare two values in single query and then return only the bigger one? I have a table where 2 cols 'country' and 'count'.

like: which country has bigger count, Germany or Sweden? Then return (print) the one, that has bigger value.

I could do this with PHP, but i need a query this time (so i can query MySQL directly with SSH).

Thanks.
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

this isn't probably exactly correct ( not able to try this query out, so just basing what i think might work on this ), but you get the overall idea. you want to get the count of both fields, and choose which one is bigger. there might be a more simple way to do this, but i'm the kinda person that just gets the values and then does all his value checks in php rather than the query... so anyways, try this and see what it gets ya :

Code: Select all

$sql = "SELECT count(country) as first_val, count(count) as second_val from mytable having first_val > 0";
$result = mysql_query($sql) or die(MySQL_Error());
while($row=mysql_fetch_array($result))
{
   if($row['first_val'] > $row['second_val'])
   {
      echo 'Country was bigger';
   }
   else
   {
       echo 'Count was bigger';
   }
}
Post Reply