Drupal 6 has a lot of database API commands, although one common task that continues to come up is how to get results out of a query more than once, without repeating the query. I've not seen this documented elsewhere so I thought it was worth noting.
Why bother?
Excellent question. Shouldn't I have written a better query? Our need was to go through the resultset from the db_query and work out the highest and lowest values, then, perform some complex maths on each row that depended on knowing the highest and lowest values.
One possibility was to perform an extra two queries, getting high and low values, but this turned out to be slow. Another would be to order the original query from lowest to highest and just cherry-pick the start and end values, although the ORDER BY on the query turned out to be slow enough to be cumbersome.
It's as easy as...
Assuming we have a $result as the result of a db_query(), we just need to $result->data_seek(0):
- $highest = 0;
- $lowest = NULL;
- // Determine high and low values from the query.
- if ($record->count > $highest) {
- $highest = $record->count;
- }
- if ($lowest === NULL || $record->count < $lowest) {
- $lowest = $record->count;
- }
- }
- // Reset the pointer to the first row in the result set.
- $result->data_seek(0);
- // do complicated calculations to achieve world domination.
- }
Nice!
Comments
It sounds like you really need an index on your data set. Without knowing what your query or your data set looks like, I can't say for sure that it's going to work. But, with an index, ORDER BY, MIN(), and MAX() all work much faster. SQL really ought to be faster than PHP at this kind of thing.
Also, you can get the lowest and highest in the same query:
SELECT MIN(count) AS lowest, MAX(count) AS highest FROM foo;
Why not just store the data into an array and then iterate over that array?
I discussed an array-based method for this a while back:
http://www.garfieldtech.com/blog/php-group-by-with-arrays
The advantage there being that you could do forms of grouping and clustering you cannot do in straight SQL.










