【问题标题】:select last inserted row based on date根据日期选择最后插入的行
【发布时间】:2021-02-21 15:41:59
【问题描述】:

主要问题是:-根据日期选择最后插入的行

我希望能够选择具有最后 created_At 日期的不同参考行。

这是我的表格和数据

DROP TABLE IF EXISTS `transactions_logs`;
CREATE TABLE IF NOT EXISTS `transactions_logs` (
  `trans_log_Id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `etat_de_commande` varchar(100) NOT NULL,
  `ref` varchar(10) NOT NULL,
  `commentaire` text NOT NULL,
  `staffId` bigint(20) UNSIGNED NOT NULL,
  `Created_At` datetime NOT NULL,
  PRIMARY KEY (`trans_log_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

INSERT INTO `transactions_logs` (`trans_log_Id`, `etat_de_commande`, `ref`, `commentaire`, `staffId`, `Created_At`) VALUES
(1, 'waiting confirmation', '429735061', '', 1, '2020-11-09 12:11:43'),
(2, 'waiting confirmation', '472143970', '', 1, '2020-11-09 13:45:57'),
(3, 'confirmed', '429735061', '', 1, '2020-11-09 13:46:12'),
(4, 'ready', '429735061', '', 1, '2020-11-09 13:46:18'),
(5, 'picked', '429735061', '', 1, '2020-11-09 14:46:25');
COMMIT;

我希望能够得到这个结果

(2,'waiting confirmation','472143970',1,'2020-11-09 13:45:57'),
(5,'picked','429735061',1,'2020-11-09 14:46:25')

【问题讨论】:

    标签: mysql sql codeigniter datetime greatest-n-per-group


    【解决方案1】:

    一个选项使用窗口函数,在 MySQL 8.0 中可用:

    select *
    from (
        select t.*, 
            rank() over(partition by ref order by created_at desc) rn
        from transactions_logs t
    ) t
    where rn = 1
    

    您还可以使用关联子查询进行过滤 - 这适用于所有 MySQL 版本:

    select t.*
    from transactions_logs t
    where t.created_at = (
        select max(t1.created_at)
        from transactions_logs t1
        where t1.ref = t.ref
    )
    

    后者将利用(ref, created_at) 上的索引。

    【讨论】:

    • 我可以为 ref 添加一个数组,例如“where ref in (array)”
    • where ref in (array) 是什么意思?
    • 我的意思是我想传递具有特定值的数组,该值必须是其中之一
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2021-02-02
    • 2022-01-25
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多