Re: grabbing the range

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



blackwater dev wrote:
> Let's say I have 100 rows in the database, I need to loop throw them
> ten at a time and for each set grab the max and min ages...I then need

You really want the min/max of just the 10 on screen?...

Okay. [shrug]

At that point you need to use a sub-query -- which is only supported in
more recent MySQL -- or you can run two queries separately.

Solution 1 (sub-query):
select min(age), max(age) from (select age from customers limit 10, 20)

Solution 2 (two queries):
select ID from customers limit 10, 20
<?php
while (list($id) = mysql_fetch_row($customers)){
  $ids[] = $id;
}
$ids_sql = implode(', ', $ids);
$query = "select min(age), max(age) from customers where id in ($ids_sql)";

> to return a multi-dimensional array of all the ranges...I basically
> want to do this but of course this query won't work:
>
> ***this is just pseudo code***
>
> I would run this query for each set and return max and min ages into the
> array.
>
>      select max(age) as max_age, min(age) as min_age
> 			    	  from customers  limit 10,20;
>
> How should I do this?  Do I have to run a query like this:
>    select  age from customers limit 10,20
>
> and loop through the result set putting all these values into an array
> and then pull the min and max out of the array?

While that would work, it's generally faster to let MySQL do the work of
sorting/searching...

If you're not using the sub-query solution, however, there probably isn't
a whole lot of advantage to running a second query instead of just
tracking min/max as you loop through your results:

$max = 0;
$min = 20000; //Older than Methusela
$query = "select age from customers limit 10, 20";
$customers = mysql_query($query) or trigger_error(mysql_error() . "
$query", E_USER_ERROR);
while (list($age) = mysql_fetch_row($customers)){
  $min = min($min, $age);
  $max = max($max, $age);
}

Since you're always looping through 10 rows either way, the PHP min/max
will probably be about the same as doing another query.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux