我有两个表
customer_master
> cname
> lastreceiptdate
> lastreceiptamt
accounts
> cname
> date
> amount
我需要帮助构建单个更新查询。其中更新了customer_master
表的最新收据日期和收据金额(例如" frualxxxxx")从Account表中进行。
它应该在MySQL 5.0和PostgreSQL 9.0
中工作谢谢
到目前为止update customer_master
set receiptdate = @_da, receiptamt=@_amt
where cname = @_cn and (receiptdate < @_da or receiptdate='null')
如果您需要为所有客户执行此操作,它将是 lot 更快地截断表并插入所有内容去:
truncate table customer_master;
insert into customer_master (cname, lastreceiptdate, lastreceiptamt)
select cname, last_date, last_amount
from amounts
join (
select cname,
max(date) as max_date
from accounts
group by cname
) ma on ma.max_date = amounts.date
and ma.cname = amounts.cname
这是最大的想法。日期是"唯一",即accounts
中不存在同一日期的两个行。
如果您真的要每次更改表,您真的想更新表,您可以使用类似的东西:
update customer_master
set lastreceiptdate = last_date,
lastreceiptamt = last_amount
from (
select cname, last_date, last_amount
from amounts
join (
select cname,
max(date) as max_date
from accounts
group by cname
) ma on ma.max_date = amounts.date
and ma.cname = amounts.cname
) as t
where customer_master.cname = t.cname
and customer_master.cname = 'some customer name';
customer_master.cname = 'some customer name'
运行单个客户的更新,而不是全部。(我不知道这是否会在MySQL中工作)
请注意,您确实需要按语句加入该组,以获取"属于"最新收据的正确金额。
如果您使用简单
select cname,
max(date),
max(amount)
from accounts;
返回的最大值。金额不一定"属于"最大。日期(可能是不同日期的金额)。