我知道這是一個常見的問題,因爲我之前已經問過它,並且已經查看了更多,但儘管基於我的查詢,我仍然無法使其工作。見:Mysql join based on max(timestamp)和mysql LEFT join for right table max valueMySQL - 左加入MAX時間戳
基本上我有一個不同的項目表('椅子','表'),並且每種類型都有自己的特定椅子或桌子的ID的記錄。然後我有一個位置表,它保留了所有曾經的位置,包括當前位置。當前位置由MAX時間戳記錄。
我的查詢是爲了獲取所有項目,並加入到當前位置。我遵循其他人所說的作品,但它不適合我。任何幫助表示讚賞。
編輯:我沒有說它是如何失敗的:它獲取記錄並進行連接,並返回最大時間戳,但不是與MAX(時間戳記錄)對應的記錄信息。所以它給出了正確的時間戳,但是發言權等不是來自具有MAX時間戳的記錄。
謝謝!
查詢:
$q = "SELECT
'chairs' AS work_type,
chairs.id AS work_id,
chairs.title,
chairs.dimensions,
CurrentLocations.floor,
CurrentLocations.bin,
CurrentLocations.bay,
CurrentLocations.other
FROM chairs
LEFT JOIN (
SELECT
locations.id AS loc_id,
locations.work_type AS clwt,
locations.work_id AS clwi,
locations.floor,
locations.bin,
locations.bay,
locations.other,
MAX(locations.timestamp) AS latestLocation
FROM
locations
GROUP BY
locations.work_type, locations.work_id
) CurrentLocations
ON CurrentLocations.clwi = chairs.id AND CurrentLocations.clwt = 'chairs'
WHERE cur_loc LIKE '%19th Street%'
ORDER BY
FIELD(floor, 'Basement', '3rd Floor', '4th Floor', '5th Floor'),
bin,
bay,
other";
怎麼沒有工作,你得到了什麼錯誤?你得到錯誤的結果? –
是的,對不起,這對我來說是無知的:它給出結果,但它選擇的位置記錄不是基於最新的時間戳。 – dgig
首先,您通常應該通過GROUP BY給定SELECT子句中的每個未聚合字段。例如。 SELECT field1,field2,MAX(field3)FROM my_table GROUP BY field1,field2;此外,您的位置表看起來像需要正常化。 – Strawberry