【发布时间】:2013-01-16 22:36:18
【问题描述】:
我知道这是一个常见问题,因为我之前已经问过这个问题,并且已经看了几个,但是,尽管我的查询基于此,我仍然无法让它发挥作用。请参阅:Mysql join based on max(timestamp) 和 mysql LEFT join for right table max value
基本上,我有一张包含不同物品(“椅子”、“桌子”)的桌子,每种类型都有针对特定椅子或桌子的带有自己 ID 的记录。然后我有一个位置表,其中保存了所有曾经的位置,包括当前位置。当前位置由 MAX 时间戳记。
我的查询旨在获取所有项目,并加入到当前位置。我遵循了其他人所说的有效方法,但它对我不起作用。任何帮助表示赞赏。
编辑:我没有说它是如何失败的:它获取记录并进行连接,它返回最大时间戳,但不返回与 MAX(timestamp) 记录对应的记录信息。所以它给出了正确的时间戳,但地板等不是来自具有 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";
【问题讨论】:
-
怎么没用,你遇到了什么错误?你得到错误的结果?
-
是的,对不起,我不知道:它给出了结果,但它选择的位置记录不是基于最新的时间戳。
-
首先,您通常应该对给定 SELECT 子句中的每个未聚合字段进行 GROUP BY。例如。 SELECT field1,field2,MAX(field3) FROM my_table GROUP BY field1,field2;此外,您的位置表看起来需要标准化。