加入来自 child table 的最新行的第一行

Join first row of the latest rows from child table

我有 2 个表 bookingsport_movements

bookings 有很多 port_movements

bookings 列:id,closed
port_movements 列:id,booking_id,date

如何 return bookings 列出 where closed = false 并仅加入 1 来自 bookings.id = port_movements.booking_id 端口移动的最新行以避免重复

这是我的代码

$query
->where('closed', false)
->join('port_movements as pm', 'bookings.id', '=', 'pm.booking_id')
->where(function ($q) {
       $q->where('pm.type', 'berthing')
         ->orWhere('pm.type', 'shifting');
})
->join('vessels', 'bookings.vessel_id', '=', 'vessels.id')
->join('berths', 'lm.berth_id', '=', 'berths.id')
->whereIn('berths.id', $berths);

我注意到你有 SQL 标签,所以我会用 SQL 解决方案来回答。

如果您不想这样,请指定 laravel 并仅关联 ...

查询将是:

WITH newest_port_movements AS (
  SELECT
    booking_id
  , MAX("date") AS max_dt -- it is a reserved word, put in quotes
  FROM port_movements
  WHERE NOT closed
  GROUP BY booking_id
)
SELECT
  b.*
, pm.*
FROM bookings b
JOIN newest_port_movements npm
  ON b.id = npm.booking_id
 AND NOT b.closed
JOIN port_movements pm
  ON npm.booking_id = pm.booking_id
 AND npm.max_dt     = pm."date"
 AND NOT pm.closed
;

查询会是这样;

SELECT *
FROM bookings
         join port_movements as pm on pm.booking_id = bookings.id and
                                          pm.date = (SELECT MAX(date)
                                                         FROM port_movements
                                                         WHERE port_movements.booking_id = bookings.id)
where closed = false;

查询生成器;

return DB::table('bookings')
            ->join('port_movements as pm', function ($join) {
                $join->on('pm.booking_id', '=', 'bookings.id');
                $join->on('pm.date', '=', DB::raw('(SELECT MAX(date) FROM port_movements WHERE port_movements.booking_id = bookings.id)'));
            })
            ->where('closed', false)
            ->get();

子查询部分不是我最擅长的,可能有更好的方法。