Return the data from the rows with the most recent date of each distinct candidate_id

后端 未结 2 975
刺人心
刺人心 2021-01-05 06:40

I am attempting to return the data from the rows with the most recent date of each distinct candidate_id. It is correctly returning the most recent date (the created_unix co

2条回答
  •  隐瞒了意图╮
    2021-01-05 07:25

    You must group by everything not using an aggregate function:

    SELECT candidate_id, message, max(created_unix), jobpost_id, staffuserid 
        FROM messages 
           WHERE employer_id='$employerid' AND last='company' 
              GROUP BY candidate_id, message, jobpost_id, staffuserid 
    

    If your message is different per row and you want to group by candidate_id, then you must not be using message. In that case, simply remove it from your select list and you won't need it in your group by list. The same goes for any other field you aren't using.

    Remember, when using aggregate functions, you must contain each field in either an aggregate function or the group by. Otherwise, SQL won't know from which row to pull the data for the row returned.

    Update:

    After seeing what you're looking for, this will do the trick:

    SELECT candidate_id, message, max(created_unix), jobpost_id, staffuserid 
        FROM messages 
           WHERE employer_id='$employerid' AND last='company' AND
           created_unix = (
               SELECT max(subm.created_unix)
               FROM messages subm
               WHERE subm.candidate_id = messages.candidate_id
           )
    

提交回复
热议问题