从连接表中选择记录时,如果可能,从每个A表记录的B(已加入)表中获取最新记录

时间:2017-10-11 13:08:29

标签: mysql greatest-n-per-group

我有历史记录表,并加入了一个评论表。两者都有日期 - 所以创建了历史记录,并且有一个评论表,用于记录针对该历史记录的评论。

当我询问表格时,我想要所有的历史记录,以及每个记录的最新评论。不幸的是,我似乎没有按照我的意愿获取数据,因为如果将注释添加到先前的历史记录中,那么此查询将返回最新的历史记录(正确)但最新的评论总体(不正确)而不是我正在查看的历史记录的最新评论。

这是我们的MySQL

SELECT h.id
     , c.id comment_id
     , c.comment recent_comment
     , h.* 
  FROM crm_device_history h 
  LEFT 
  JOIN crm_device_history_comments c 
    ON c.crm_device_history_id = h.id 
   AND c.id = ( SELECT max(id) 
                  FROM crm_device_history_comments  
                 WHERE c.crm_device_history_id = h.id ) 
 WHERE device_id = 147 
   AND crm_history_states_id >= 0 
 ORDER 
    BY h.id DESC 

crm_device_history表

id
device_id
crm_history_states_id
userID
dateTime
system_comment
comment -> this field is to be dropped now we have a separate table
distributor_assignment
client_assignment
updated_date
created_date

crm_device_history_comments

id
crm_device_history_id
comment
user_id
updated_date

2 个答案:

答案 0 :(得分:0)

尝试这个

    SELECT 
        h.id,
        sub_query.id AS comment_id,
        c.comment as recent_comment,
        h.*
    FROM
        crm_device_history h 
    INNER JOIN
        (SELECT 
             max(id) as id,
             crm_device_history_id 
         FROM 
             crm_device_history_comments
         GROUP BY 
             crm_device_history_id)
         AS sub_query ON sub_query.crm_device_history_id = h.id
    INNER JOIN
        crm_device_history_comments  AS c ON c.id = sub_query.id
    WHERE device_id = 147 AND h.crm_history_states_id >= 0 
    ORDER BY h.id DESC 

答案 1 :(得分:-1)

试试这个

SELECT h.id,
       c.id      AS comment_id,
       c.comment AS recent_comment,
       h.*
FROM   crm_device_history h
       LEFT JOIN (SELECT Max([date]),
                         id
                  FROM   crm_device_history_comments
                  GROUP  BY id) c
              ON c.crm_device_history_id = h.id
WHERE  device_id = 147
       AND crm_history_states_id >= 0
ORDER  BY h.id DESC