简体   繁体   English

SQL/PSQL function 从内部联接表获取最新更新

[英]SQL/PSQL function to get latest update from inner joined table

I have 2 tables: drivers and drivers_locations .我有 2 个表: driversdrivers_locations I want to create a computed field in the drivers table that returns the last inserted location of a driver.我想在drivers表中创建一个计算字段,该字段返回驱动程序的最后插入位置。

The drivers_locations table has these columns: drivers_locations表有以下列:

- id: uuid
- driver_id: uuid
- location: geography
- timestamp: bigint

The timestamp is in milliseconds since the unix epoch. timestamp是自 unix 纪元以来的毫秒数。 (eg 1673129623999). (例如 1673129623999)。

Here is my noobish failed attempt at achieving this:这是我在实现这一目标时失败的失败尝试:

CREATE OR REPLACE FUNCTION public.fn_driver_last_location(driver_row drivers)
    RETURNS geometry
 LANGUAGE sql
 IMMUTABLE
AS $function$
    SELECT loc.location 
    FROM driver_locations loc
    inner join drivers drv
    on loc.driver_id  = drv.id
    group by loc.location_recorded_time_unix, loc.location, drv.id
    HAVING loc.location_recorded_time_unix = MAX(loc.location_recorded_time_unix) and drv.id = driver_row.id;
$function$
;;

Any ideas?有任何想法吗?

You can sort the locations by the time and limit the result to one row.您可以按时间对位置进行排序并将结果限制为一行。 You also don't need the join.您也不需要加入。

CREATE OR REPLACE FUNCTION public.fn_driver_last_location(driver_row drivers)
 RETURNS geometry
 LANGUAGE sql
 STABLE
AS $function$
    SELECT loc.location
    FROM driver_locations loc
    where loc.driver_id = driver_row.id
    order by loc.location_recorded_time_unix desc 
    limit 1;
$function$
;

A function that selects from a database tables should never be declared as immutable as it can return different results even when called with the same parameter.从数据库表中选择的 function 永远不应声明为immutable的,因为即使使用相同的参数调用它也可能返回不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM