我知道这是一个常见问题,因为我之前已经问过这个问题,并且已经看了几个,但尽管我的查询基于此,我仍然无法让它发挥作用。参见:Mysql join based on max(timestamp) and 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";