为了账号安全,请及时绑定邮箱和手机立即绑定

使用相同的列值更新数据库的最新行

使用相同的列值更新数据库的最新行

慕斯709654 2022-12-06 16:40:31
我有一个如下表:------------------------------------------------------| year     |  period     |  publish_date |  status   |-----------|-------------|---------------|-----------||  2020    |     03      |  datetime_obj |     0     ||  2020    |     03      |  ...          |     0     ||  2020    |     03      |  ...          |     0     ||  2020    |     03      |  ...          |     0     ||  2020    |     04      |  ...          |     0     ||  2020    |     04      |  ...          |     0     |------------------------------------------------------我想更新任何年份和时期组的最新发布日期的状态,但我对此一无所知例如:选择周期为 03 的 2020 年的所有行,然后将最新的 publish_date 的状态更新为 1,然后对周期为 04 的 2020 年执行相同的操作直到结束......我想在 django 中使用它所以请用 pythonic 方式解释或者sql查询这是我的 Django 模型:class Balance_Sheet(models.Model):    ...    publish_date = models.DateTimeField(auto_now=True)     year = models.IntegerField(null=True)    period = models.IntegerField(null=True)     status = models.IntegerField(default=0)      ...太感谢了
查看完整描述

3 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

解决方案 1


一个简单的方法是迭代年/月应用过滤器:


years = {sheet.year for sheet in Balance_Sheet.objects.all()}


for year in years:

  year_months = {sheet.month for sheet in Balance_Sheet.objects.filter(year=year)}


  for month in year_months:

    object_to_update = Balance_Sheet.objects.filter(

      year=year,

      period=month

    ).order_by('-publish_date').first()


    object_to_update.status = 1

    object_to_update.save()

可能有更复杂的 ORM 函数来将其变成单个查询,但我在那里编写的代码(未测试)将在大多数/所有 Django 版本中工作。此外,由于我们谈论的是年/月数量,因此对数据库的查询量不会很大。


方案二


在 postgres 数据库中,你可以试试这个:


Balance_Sheet.objects.all().order_by(

    'year', 'period', '-publish_date'

).distinct(

    'year', 'period'

).update(

    status=1

)

请注意,这不适用于其他数据库,例如 MySQL。请在此处查看 django 文档。



查看完整回答
反对 回复 2022-12-06
?
慕容森

TA贡献1853条经验 获得超18个赞

这在 mysql 中工作


UPDATE Balance_Sheet b

    INNER JOIN (SELECT max(publish_date) LastDate, year, period FROM bs GROUP BY year, period) C

    ON C.LastDate = b.publish_date and C.period = b.period and C.year = b.year

SET b.status = 1

where C.LastDate = b.publish_date and C.period = b.period and C.year = b.year

谢谢大家


查看完整回答
反对 回复 2022-12-06
?
Qyouu

TA贡献1786条经验 获得超11个赞

我不熟悉 django 但它的 sql 看起来像这样。由于您已经有了资产负债表。您只需要更新部分。


WITH balance_sheet(id ,yearmonth , publish_date, status)

AS (SELECT 1, '202003',  '2020-03-10' , 0   UNION 

    SELECT 2, '202003',  '2020-03-15' , 0   UNION

    SELECT 3, '202004',  '2020-04-20' , 0   UNION

    SELECT 4, '202004',  '2020-04-25' , 0

   )


UPDATE b

SET status = 1

FROM balance_sheet b

JOIN (Select *,RANK() OVER (partition by yearmonth ORDER BY publish_date desc) AS rnk 

from balance_sheet bal) b_latest ON b.id = b_latest.id

WHERE b_latest.rnk = 1


查看完整回答
反对 回复 2022-12-06
  • 3 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号