2017-10-11 72 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