简体   繁体   中英

How to select max date?

My code is

function lister($a,$con){
    $queryq = " SELECT * FROM note WHERE date= MAX(date)  AND id='".$a."' AND admin='".$_SESSION['login_username']."' ";
    $resultq = mysqli_query($con,$queryq) or die('Error: ' . mysqli_error($con));
    $arrayq=mysqli_fetch_array($resultq,MYSQL_NUM); {
        echo $arrayq[4];
    }
}

There is an error:

Error: Invalid use of group function

What am I doing wrong?

try to split the query

         $queryA = "SELECT date FROM `note` WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' ORDER BY date DESC LIMIT 1";
         $resultA = mysql_query($con, $queryA);
         $maxDatePerUser = mysql_fetch_array($resultA);
         $queryq = " SELECT * FROM note WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' AND date='" . $maxDatePerUser["date"] ."'";
         $resultq = mysqli_query($con,$queryq) or die('Error: ' . mysqli_error($con));
         $arrayq=mysqli_fetch_array($resultq,MYSQL_NUM); {

The problem is caused by a circular reference of sorts.

SELECT * FROM note WHERE date= MAX(date)  AND id='".$a."' AND admin='".$_SESSION['login_username']."' "

You're asking the function to calculate something based on that same thing - a condition of the statement is MAX(date), but it can't calculate that until it knows what it is.

The best solution is to find MAX(date) separately:

SELECT max(date) FROM note

You can add additional restrictions, if necessary, if it is the max date WHERE, ie

SELECT max(date) FROM note WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' "

Once you have this, you can pop it back in the query:

SELECT * FROM note 
   WHERE date = (SELECT max(date) 
                  FROM note 
                  WHERE id = '" . $a . "' 
                  AND admin = '" . $_SESSION['login_username'] . "')  
   AND id = '" . $a . "' 
   AND admin = '" . $_SESSION['login_username'] . "';

Hard to get the query 100% right without having the data to test on, but that should work.

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