使用group by获取字段的最新值

时间:2017-01-30 09:48:26

标签: mysql sql group-by sql-order-by

我正在进行查询,其中我希望将作业ID分组,但我希望结果中没有发生的最新时间戳行

这是SQL小提琴

http://sqlfiddle.com/#!9/de8769

表的普通视图是

enter image description here

使用此查询后的输出

SELECT 
DISTINCT(user_id),
job_id,
message,
receiver_id,
parent,
type,
id as id FROM ai_ms_messages 
WHERE (receiver_id = '7' OR user_id = '7') AND type<>0 AND type<>2 group by job_id 
ORDER BY  max(timestamp) DESC

enter image description here

但是正如你可以看到它将id的值取为3作为job_id 11但它应该取值5(因为这是job_id 11的最新值)并且顺序错误。由于job_id 11最新不是job_id 12.有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

查询将是:

select 
distinct(m1.user_id),
m1.job_id,
m1.message,
m1.receiver_id,
m1.parent,
m1.type,
m1.id as id from ai_ms_messages as m1
where m1.type<>0 and m1.type<>2
and m1.timestampt = (select max(m2.timestamp) from ai_ms_messages as m2 where m2.job_id = m1.job_id)

答案 1 :(得分:0)

根据您的查询,您正在查找receiver_id = '7'id =5 , receiver_id = '6'的数据,因此这不在您的查询输出中。

只需删除where条件,或仅根据条件检查数据。

GROUP BY组在它遇到的第一个匹配结果上。

因此,它最好将此方法作为子查询。

SELECT * 
FROM (

SELECT DISTINCT (
user_id
), job_id, message, receiver_id, parent, 
TYPE , id AS id
FROM ai_ms_messages
WHERE (
receiver_id =  '7'
OR user_id =  '7'
)
AND TYPE <>0
AND TYPE <>2
ORDER BY TIMESTAMP DESC
) AS sub
GROUP BY job_id