我正在使用以下代码来获取航程类型及其各自航程的分组列表。
public function getVoyageTypesWithTrips() {
//query
$this->db->query('
SELECT voyagetype_name
, voyagetype_description
, voyagetype_image
, voyage_id
, voyage_name
, voyage_startDate
FROM voyagetypes
LEFT
JOIN voyages
ON voyagetypes.voyagetype_id = voyages.voyage_type
WHERE voyagetype_deleted != 1
');
//get the results
$results = $this->db->resultSetGrouped();
return $results;
}
//get results set as array of objects - grouped
public function resultSetGrouped() {
$this->execute();
return $this->statement->fetchAll(PDO::FETCH_GROUP);
}
我想做的是将航行表限制为仅显示到今天为止最接近的3条记录,而不是返回该类型的所有航行。
所以回来
我最初尝试使用ORDER BY和LIMIT,但是我认为这不适用于PDO :: FETCH_GROUP。
我相信我需要先获得我的SQL命令并限制连接表,然后才能发送到fetch_group ????所以像
$this->db->query('
SELECT voyagetype_name
, voyagetype_description
, voyagetype_image
, voyage_id
, voyage_name
, voyage_startDate
FROM voyagetypes
LEFT
JOIN voyages
ON voyagetypes.voyagetype_id = voyages.voyage_type
APPLY THE SORT AND LIMIT TO THE JOINED TABLE
WHERE voyagetype_deleted != 1
');
一个选项是使用子查询进行过滤:
select vt.voyagetype_name, vt.voyagetype_description, vt.voyagetype_image, v.voyage_id, v.voyage_name, v.voyage_startdate
from voyagetypes vt
left join voyages v
on v.voyagetype_id = vt.voyage_type
and v.voyage_startdate >= (
select v1.voyage_startdate
from voyages v1
where v1.voyage_type = vt.voyage_type
order by v1.voyage_startdate desc
limit 2, 1
)
where vt.voyagetype_deleted <> 1
或者,如果您正在运行MYSQL 8.0,则可以只使用row_number()
:
select *
from (
select
vt.voyagetype_name,
vt.voyagetype_description,
vt.voyagetype_image,
v.voyage_id,
v.voyage_name,
v.voyage_startdate,
row_number() over(partition by vt.voyage_type order by v.voyage_startdate desc) rn
from voyagetypes vt
left join voyages v on v.voyagetype_id = vt.voyage_type
where vt.voyagetype_deleted <> 1
) t
where rn <= 3