简体   繁体   中英

Know lower value and its column name from select

I have a PHP document with MySQL database storing with the following structure:

  • DATE FIELD
  • 24 float values corresponding to the 24 hours. (The name is 1h, 2h, 3h, 4h... 24h)

I fetch a row with the simple select: SELECT * from table where DATE = "2014-02-02" obtaining the 25 fields.

I want to know wich field of 1h, 2h, 3h.... has the lower value. I'm trying doing that with PHP and min() function, but I only retreive the value, not the index of the array.

Is this possible a simple way to know this result? Maybe in the SQL function?

Thank you

EDIT: I tried this (Considering $arraySQL has a valid result obtained before):

     function ObtainArrayFromSQL($arraySQL){
     $array = array();
     for ($i = 1; $i < 25; $i++)
          {
              array_push($array, $data_day[$i."h"]);
          }
     return $array;
     }
     [...]

     $array = ObtainArrayFromSQL($arraySQL)
     echo min($array);

Assuming you are using MySQL, you can use the least() function:

select t.*,
       (case when col1 = leastval then 'col1'
             when col2 = leastval then 'col2'
             when col3 = leastval then 'col3'
             . . .
             when col24 = leastval then 'col24'
        end) as leastvalcol   
from (select t.*,
             least(col1, col2, . . . , col24) as leastval
      from table t
     ) t;

Before complaining about all the typing you need, you should know that this query is much more complicated than it needs to be -- because you are storing things on a row that should be in a column. Your table should have a separate row for each hourly value, rather than putting all the daily values on one row. With a more normalized structure, your query would be much simpler.

EDIT:

This table would have columns such as:

Date date,
Hour time,  -- or int or varchar() depending on how you really want it captured
Value float

Then the query might look like:

select date, min(value) as minvalue,
       substring_index(group_concat(hour order by value asc), ',', 1) as minhour
from newtable t
group by date;

At first, thank you everyone for the help.

Finally I made the solution with PHP instead of manipulate a big SQL sentence.

I create the array using the function ObtainArrayFromSQL, and then, use the function array_search() with min() as needle in the haystack (array).

 function ObtainArrayFromSQL($arraySQL){
 $array = array();
 for ($i = 1; $i < 25; $i++)
      {
          array_push($array, $data_day[$i."h"]);
      }
 return $array;
 }
 ...

$index_lower_value =  array_search(min($array), $array);

Thank you everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM