返回每个不同的candidate_id具有最新日期的行中的数据
我试图从每个不同的candidate_id 的最新日期的行返回数据。它正确返回最近的日期(created_unix 列),但不返回相应行的其余数据。
SELECT candidate_id, message, max(created_unix), jobpost_id, staffuserid
FROM messages
WHERE employer_id='$employerid' AND last='company'
GROUP BY candidate_id
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 column), but not the rest of the data from the corresponding row.
SELECT candidate_id, message, max(created_unix), jobpost_id, staffuserid
FROM messages
WHERE employer_id='$employerid' AND last='company'
GROUP BY candidate_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须对不使用聚合函数的所有内容进行
分组
:如果您的
消息
每行都不同,并且您想要按candidate_id分组
,那么您必须没有使用消息
。在这种情况下,只需将其从选择列表中删除,您的group by
列表中就不再需要它了。对于您不使用的任何其他字段也是如此。请记住,使用聚合函数时,必须将每个字段包含在聚合函数或
group by
中。否则,SQL 将不知道从哪一行提取返回行的数据。更新:
看到您要查找的内容后,这将解决问题:
You must
group by
everything not using an aggregate function:If your
message
is different per row and you want togroup by candidate_id
, then you must not be usingmessage
. In that case, simply remove it from your select list and you won't need it in yourgroup 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:
这会将
messages
与 Candidate_id 上的自身连接起来,并生成带有选择m2
中大于m1
中每个日期的所有日期的行,替换如果没有更大的,则为 NULL
。因此,当candidate_id
中没有更大的日期时,您会准确地得到NULL
。This joins
messages
to itself on candidate_id and makes rows with picks all dates inm2
that are greater than each date inm1
, substitutingNULL
if none are greater. So you getNULL
precisely when there is no greater date within thatcandidate_id
.