2017-10-11 26 views
-1

我有历史记录表并加入了一个备注表。两者都有日期 - 所以创建了历史记录,并且有一个评论表,它记录了对该历史记录的评论。当从连接表中选择记录时,如果可能,从B(加入)表中获取每个A表记录的最近记录

当我询问表格时,我需要所有历史记录以及每个记录的最新评论。不幸的是,我似乎没有按照自己的意愿获取数据,因为如果将评论添加到较早的历史记录中,则此查询将返回最近的历史记录(正确),但会返回最近的整体评论(不正确)而不是我正在看的历史记录的最新评论。

这里是我们的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 
+0

什么是您预期的结果? –

+1

在您的问题中添加模式,样本数据,当前和预期结果。这真的很有帮助。 –

+0

所以我期望看到最近的历史记录(h.id),并在该行中看到与它有关的最新评论(recent_comment)。我实际得到的是最近的历史记录,但也是最新的评论(所以评论表中的最新评论,而不是最新的,适用于我正在查看的历史记录的评论) – Rich

回答

-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 
+0

欢迎来到Stack Overflow!感谢您的代码片段,它可能会提供一些有限的即时帮助。通过展示*为什么*这是一个很好的解决方案,并且使它对未来的读者更有用,一个正确的解释[将大大提高](// meta.stackexchange.com/q/114762)其长期价值其他类似的问题。请[编辑]你的答案以添加一些解释,包括你所做的假设。 –

+0

好的这段代码片段在字段列表中返回一个未知列c.comment .. – Rich

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 
+0

差不多 - 我为历史记录返回的评论是最近对历史记录的评论ID,但是recent_comment仍然来自不同的记录.. – Rich

+0

出现错误,我在select中选择了recent_comment之后放置了一个逗号,现在我在ON子句中得到'未知列crm_device_history_id' – Rich

+0

不完全 - #1054 - 'on子句'中未知列'crm_device_history.id'。如果我将h替换为h.id,我会得到记录,但只有四个记录,而不是最近对历史记录的评论。这是一个弯曲头! – Rich