我有歷史記錄表並加入了一個備註表。兩者都有日期 - 所以創建了歷史記錄,並且有一個評論表,它記錄了對該歷史記錄的評論。當從連接表中選擇記錄時,如果可能,從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