I have a task - search and output of min and max values from two columns of the table.
An example of the values of the cells of the table TABLE :
ID |S-MIN|S_MAX 0 |10 |31 1 |4 |8 2 |6 |0
Search for min and max is necessary only among the values greater than zero.
I could only portray such a solution:
Script
//ищу минимум в первом столбце $smin=mysql_fetch_array(mysql_query("SELECT `S_MIN` FROM `table` ORDER BY `S_MIN` ASC limit 1")); //ищу максимум в первом столбце $sminmax=mysql_fetch_array(mysql_query("SELECT `S_MIN` FROM `table` ORDER BY `S_MIN` DESC limit 1")); //ищу максимум во втором столбце $smax=mysql_fetch_array(mysql_query ("SELECT `S_MAX` FROM `table` ORDER BY `S_MAX` DESC limit 1")); //if нужен на случай, если максимальное значение таблицы будет лежать в первом столбце if ($smax < $sminmax) echo "Минимум=".$smin[0].", максимум=".$sminmax[0].""; else echo "Минимум=".$smin[0].", максимум=".$smax[0]."" ;
Thinking that 3 queries in the database is not good, I began to move towards optimization, and I still did not move to the end.
That's how I came to this state:
Optimization
//извлекаем все значения талицы в массив $query = "SELECT `S_MIN`, `S_MAX` FROM `table`"; $result = mysql_query($query) or die(); $array = mysql_fetch_array($result, MYSQL_ASSOC); //сортируем все значения в массиве (при этом, как я понял происходит переиндексация) sort ($array); //и удаляем первый элемент массива, который скорее всего ноль. //сейчас понял, что нельзя просто так удалять первый элемент, ведь в таблице может и не быть нулей unset($array[0]); //дальше все просто $smin = min($array); $smax = max($array); echo "Минимум=".$smin[0].", максимум=".$smax[0]."";
Tell me where the error in my version of the optimization. And in general, is the game worth the candle?
I repeat, the first script is working.
Oh, and yes, I am not puzzled by the search for a minimum in the second column, because the data structure is such that it cannot be there by definition.