我正在使用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;
由于allowcountcount,因此每天只允许2个广告位,因此前2条记录应更新为有效= true
预期结果
UPDATE tmpSlots t1 SET valid=1
FROM (
...........
.
GROUP BY Date(StartSlot)
) AS sq
WHERE
有人可以帮我吗
答案 0 :(得分:1)
您可以在join
中使用update
。但是,您不希望聚合。相反,您可以使用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;
尽管您可以将其添加到单个更新中,但两个更新似乎更简单。