简体   繁体   中英

Function LEAST() does not work properly

I have problem with SQL LEAST function. This code should take lowest number from column named ORDER in table NAVIGATION (there are only numbers). After that - compare, if the number is(not) egual to zero. If it isn't then the code should set the first record in table column ORDER to 0. It just somehow always return the lowest number as 0 even if theres no 0 in column order. So the condition is always true.

 $sql="SELECT LEAST(999,order) FROM navigation";
        $lowest_num = mysql_query($sql) or die (mysql_error());
        if ($lowest_num != 0) {$sql2 = "UPDATE navigation SET order= '0' LIMIT 1";
            mysql_query($sql2) or die (mysql_error());
        }

What you need is the MIN() function: https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_min

"SELECT MIN(`order`) FROM navigation"

This will return the minimum value of the order column in the navigation table.

LEAST() only returns the minimum values from its arguments, and is not an aggregate function.

That query will return the least of 999 and order for each row. You need to use "SELECT MIN(order) FROM navigation" . If you still need to do the least of 999 and this minimum, you can just do:

$lowest_num = min(mysql_query($sql), 999) or die (mysql_error());

try this

  $sql="SELECT MIN(`order`) as lowest FROM navigation";

AND change this

if ($lowest_num != 0)

to

 if ( mysql_num_rows($lowest_num) != 0 )

AND change this

 UPDATE navigation SET order

to

UPDATE navigation SET `order`

EDIT:

try this

 $sql="SELECT MIN(`order`) as lowest FROM navigation";
    $lowest_num = mysql_query($sql) or die (mysql_error());
    $row = mysql_fetch_array($lowest_num) or die (mysql_error());
    if ( mysql_num_rows($lowest_num) != 0 and $row['lowest'] != 0) {$sql2 = "UPDATE navigation SET `order`= '0' LIMIT 1";
        mysql_query($sql2) or die (mysql_error());
    }

You can do these in one step with:

UPDATE navigation
    SET order = 0
    where not exists (select * from (select 1 from navigation having min(`order`) = 0))
    LIMIT 1

Or, if order is never negative:

UPDATE navigation
    SET order = 0
    where not exists (select * from (select 1 from navigation where `order` = 0))
    LIMIT 1

(As written, this is not necessarily more efficient; it is meant to capture the logic. You would write this with a join for efficiency.)

The join form is what you would want to use:

update navigation cross join
      (select min(`order`) as minorder from navigation) const
    set navigation.`order` = 0
    where const.minorder = 0
    limit 1;

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