【问题标题】:Update same table N records using group by clause使用 group by 子句更新同一张表的 N 条记录
【发布时间】:2020-10-15 19:02:09
【问题描述】:

我正在使用 Mysql 数据库,并且我有时隙表,基于允许的计数 (N) 记录的特定日期的不同时隙应该更新为有效。

CREATE  TABLE tmpSlots(
    SlotID INT AUTO_INCREMENT PRIMARY KEY  ,
    StartSlot DATETIME,
    EndSlot DATETIME,
    Valid BOOLEAN DEFAULT 0
);  
insert into tmpSlots VALUES(1,'2020-08-01 08:30:00', '2020-08-01 09:10:00',0 );
insert into tmpSlots VALUES(2,'2020-08-01 09:30:00', '2020-08-01 10:10:00',0 );
insert into tmpSlots values(3,'2020-08-01 10:30:00', '2020-08-01 11:10:00',0 );
insert into tmpSlots values(4,'2020-08-01 12:30:00', '2020-08-01 13:10:00',0 );
insert into tmpSlots values(5,'2020-08-07 08:30:00', '2020-08-07 09:10:00',0 );
insert into tmpSlots values(6,'2020-08-07 09:30:00', '2020-08-07 10:10:00',0 );
insert into tmpSlots values(7,'2020-08-07 10:30:00', '2020-08-07 11:10:00',0 );
insert into tmpSlots values(8,'2020-08-07 12:30:00', '2020-08-07 13:10:00',0 );

DECLARE permitcount INT ; 
SET permitcount =2;

作为 permitcount,因此每天只允许 2 个插槽,前 2 条记录应更新为有效 =true 预期结果

UPDATE tmpSlots t1 SET valid=1
FROM  (
  ...........
.
   GROUP  BY Date(StartSlot)
   ) AS sq
WHERE 

谁能帮我解决这个问题

【问题讨论】:

  • 已编辑我正在使用 mysql 数据库 @Gordon Linoff
  • 如果 startTime 和 endTime 在不同的日期怎么办?

标签: mysql sql database group-by


【解决方案1】:

您可以在update 中使用join。但是,您不希望聚合。相反,您可以使用row_number() 枚举每天的值。然后,使用where 子句选择每天的前两个:

update tmpslots s join
       (select s2.*,
               row_number() over (partition by date(startslot) order by startslot) as seqnum
        from tmpslots s2
       ) s2
       on s2.slotid = s.slotid
    set s.value = 1
    where s2.seqnum <= 2;

这会根据startslot 分配日期。

在早期版本中,我只使用两个更新:

update tmpslots s join
       (select date(startslot) as dte, min(slotid) as min_slotid
        from tmpslots s2
        group by dte
       ) s2
       on s2.min_slotid = s.slotid
    set s.value = 1;

update tmpslots s join
       (select date(startslot) as dte, min(slotid) as min_slotid
        from tmpslots s2
        where s.value = 0
        group by dte
       ) s2
       on s2.min_slotid = s.slotid
    set s.value = 1;

虽然您可以将其整合为一次更新,但两次更新似乎更简单。

【讨论】:

  • @Gorden Linoff 我正在使用不支持 row_number() 的 mysql 5.6 版本,或者是低于版本 8 我的 sql 的任何替代方式
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 2016-06-29
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
相关资源
最近更新 更多