Why do I get results from different row in MySQL?

FaIsal HaCk'Mé :

Using this query:

SELECT username, MAX(wordpermin) as maxword,date_created FROM user_records where DATE(date_created) = CURDATE() GROUP BY(username) ORDER BY maxword DESC LIMIT 20

I am trying to query a limit of 20 of top wordpermin by their username and the time created and that by calling date_created in the current 24h, the problem I have is when I have a new high wordpermin instead of giving me also the new date_created it keeps the old value of date_created. I even looked into my db and I made sure I have date_created updated, how can this happen I mean have two values from different rows.

nbk :

The following Query gives you the last date where a user has the maxword

Your query would not run when you activated ONLY_FULL_GROUP_BY

You should always specify for every column which aggregation function you want to use, because sql rows has no order and every column will be selected on its own.

I selected Max (date_created) , so that mysql knows which date to show, because if there were more than one date with the same max word mysql would show all

SELECT 
    u.username, u1.maxword, MAX(date_created)
FROM
    user_records u
        INNER JOIN
    (SELECT 
        username, MAX(wordpermin) AS maxword
    FROM
        user_records
    GROUP BY username) u1 ON u.username = u1.username
        AND u.wordpermin = u1.maxword
WHERE
    DATE(date_created) = CURDATE()
GROUP BY (username)
ORDER BY maxword DESC
LIMIT 20

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397645&siteId=1