我有历史记录表并加入了一个备注表。两者都有日期 - 所以创建了历史记录,并且有一个评论表,它记录了对该历史记录的评论。当从连接表中选择记录时,如果可能,从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
什么是您预期的结果? –
在您的问题中添加模式,样本数据,当前和预期结果。这真的很有帮助。 –
所以我期望看到最近的历史记录(h.id),并在该行中看到与它有关的最新评论(recent_comment)。我实际得到的是最近的历史记录,但也是最新的评论(所以评论表中的最新评论,而不是最新的,适用于我正在查看的历史记录的评论) – Rich