【问题标题】:How to use PDO::FETCH_GROUP with a table join and only returning 3 records in a joined table ordered by date如何将 PDO::FETCH_GROUP 与表连接一起使用,并且只返回按日期排序的连接表中的 3 条记录
【发布时间】:2020-09-28 15:58:12
【问题描述】:

我正在使用以下代码获取航程类型及其各自航程的分组列表。

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 条记录,而不是返回该类型的所有航次。

所以回来

  • 1 类(下周航程,下周航程,下周航程,没有更多,但在桌子上装载)
  • 2 类(明天启航,此类别不再)
  • 第 3 类(无航次)

我最初尝试了 ORDER BY 和 LIMIT,但我认为这不适用于 PDO::FETCH_GROUP。

我相信我需要在发送到 fetch_group 之前让我的 SQL 订单和限制加入的表???所以像

$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
');

【问题讨论】:

    标签: php mysql date join greatest-n-per-group


    【解决方案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 (
            select count(*)
            from voyages v1
            where 
                v1.voyage_type = vt.voyage_type 
                and v1.voyage_startdate > v.voyage_startdate 
        ) < 3
    where vt.voyagetype_deleted <> 1
    

    或者,如果你运行的是 MYSQL 8.0,你可以使用rank()

    select *
    from (
        select 
            vt.voyagetype_name, 
            vt.voyagetype_description, 
            vt.voyagetype_image, 
            v.voyage_id, 
            v.voyage_name, 
            v.voyage_startdate,
            rank() 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
    

    【讨论】:

    • 这是一个快速的答案。但它不起作用。你会得到“子查询返回不止一行”。
    • 现在,如果少于 3 个,您将一无所获:-)
    • @PaulSpiegel:是的,我已经考虑过了……我又改了。
    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多