【问题标题】:update first line of table in Postgres在 Postgres 中更新表的第一行
【发布时间】:2014-02-08 02:38:35
【问题描述】:

我有两张桌子:

Corresp 有此列:idCorresp, textCorresp ,dateCorresp
Trans 有此列:idTransf , textTransf, dateTransf,idCorresp

这是一个数据示例:

对应

001,testCorresp,2014 年 1 月 1 日

翻译

1 , T1, 01/01/2013, 001 2, T2, 01/02/2013, 001 3 , T3, 01/03/2013, 001

我想用 postgres 开发一个查询,只修改与表 corresp 相关的表 trans 的第一行

所以在此列中制作CorresptextCorresp :Trans` 的第一行的textTransf

我尝试但没有成功:

update Trans trans
set textTransf= (
select corresp.textCorresp 
from Corresp corresp , Trans trans
where corresp.idCorresp= trans.idCorresp
)
from Corresp corresp , Trans trans
where corresp.idCorresp= trans.idCorresp
and trans.dateTransf=(select min(trans.dateTransf) 
from Corresp corresp , Trans trans
where corresp.idCorresp= trans.idCorresp)

因此,在运行我的查询后,我希望在 Trans 中得到这个结果

1、testCorresp, 01/01/2013, 001 2, T2, 01/02/2013, 001 3 , T3, 01/03/2013, 001

我也试试:

更新 Trans trans3 设置 textTransf= 文本对应 从 ( 选择 Corresp .textCorresp , min(trans.dateTransf) 来自 Trans trans , Corresp corresp, Trans trans2 其中 corresp.idCorresp=trans.idCorresp 和 corresp.idCorresp=trans2.idCorresp 通过...分组 corresp.textCorresp ,trans.dateTransf ) 和 toto 在哪里 trans3.idTransf = toto.idTransf

【问题讨论】:

  • 首先——你如何定义just the first line of the table trans?是日期最少的那条线吗?具有最小 id 的行?还有什么?

标签: sql postgresql


【解决方案1】:

如果你这样尝试会怎样

update Trans set textTransf = (select textCorresp from Corresp cr join Trans tx
on cr.idCorresp = tx.idCorresp)
where idTransf = (
select idTransf 
from 
Trans t join Corresp c
on t.idCorresp = c.idCorresp limit 1
)

【讨论】:

    【解决方案2】:

    这是一般的想法。

    update trans
    set this = that, etc
    where idtransf = 
    (select min(idtransf)
    from trans
    where idCorresp = the one you want)
    

    编辑从这里开始

    对于新要求,这将适用于许多数据库引擎。希望 postgresql 是其中之一。

    update trans
    field = sqfield
    from trans join 
    (select SomeFieldFromTrans sqlfield, min(idtransf) mintrans
    from trans join corresp on the proper fields
    group by SomeFieldFromTrans ) sq ob idtransf = mintrans 
    

    【讨论】:

    • 谢谢你的回答,我已经更新了我的问题,我想运行我的查询不是在特定的 Corresp 和 Transf 中,而是在这两个表中的所有数据
    • 在工作中,当有人在我满足后更改要求时,他们欠我一杯啤酒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多