简体   繁体   中英

PHP/MySQL get max date in a clause WHERE/AND

I'm trying this in my web application:

$data = date("Y-m-d", strtotime("-15 days", strtotime(date("Y-m-d"))));

$sql = "SELECT DISTINCT(Cliente.idCliente), Cliente.nomeCliente, Cliente.email, Cliente.cpf
        FROM Cliente, Pontuacao 
        WHERE Cliente.idCliente = Pontuacao.idCliente 
        AND DATE_FORMAT(MAX(Pontuacao.timestampPontuacao), '%Y-%m-%d')='".$data."' 
        AND Cliente.receberMensagens=1 
        AND Cliente.numEstabelecimento='".$reg['numEstabelecimento']."'";

I tested the query directly in phpMyAdmin, like that:

SELECT DISTINCT(Cliente.idCliente), Cliente.nomeCliente, Cliente.email, Cliente.cpf 
FROM Cliente, Pontuacao 
WHERE Cliente.idCliente = Pontuacao.idCliente 
AND DATE_FORMAT(MAX(Pontuacao.timestampPontuacao), '%Y-%m-%d')='2016-03-28' 
AND Cliente.receberMensagens=1 
AND Cliente.numEstabelecimento=2

However, I'm getting the following error:

#1111 - Invalid use of group function

I know this is happening because the line

AND DATE_FORMAT(MAX(Pontuacao.timestampPontuacao), '%Y-%m-%d')='2016-03-28'

but I don't know how to fix that. How can I fix that?

SELECT Cliente.idCliente, Cliente.nomeCliente, Cliente.email, Cliente.cpf 
FROM Cliente
JOIN Pontuacao ON Cliente.idCliente = Pontuacao.idCliente 
WHERE Cliente.receberMensagens=1 
AND Cliente.numEstabelecimento=2
GROUP BY Cliente.idCliente, Cliente.nomeCliente, Cliente.email, Cliente.cpf 
HAVING DATE_FORMAT(MAX(timestampPontuacao)), '%Y-%m-%d') = '2016-03-28'

It looks like you could make use of HAVING .

SELECT
    DISTINCT(Cliente.idCliente),
    Cliente.nomeCliente,
    Cliente.email,
    Cliente.cpf,
    DATE_FORMAT(MAX(Pontuacao.timestampPontuacao), '%Y-%m-%d') AS max_date
FROM Cliente, Pontuacao 
WHERE
    Cliente.idCliente = Pontuacao.idCliente 
    AND Cliente.receberMensagens=1 
    AND Cliente.numEstabelecimento=2
HAVING
    max_date = '2016-03-28';

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