I have two tables
customer_master
> cname
> lastreceiptdate
> lastreceiptamt
accounts
> cname
> date
> amount
I need help in constructing a single update query. where the customer_master table is updated with the latest receipt date and receipt amount for a single customer code (cname like “FRUITXXXXX”) from accounts table.
It should work in mysql 5.0 and postgresql 9.0
thanks
so far we are using a select command to retrieve a record with max(Date) and then using another update command to update using results from the select query.
update customer_master
set receiptdate = @_da, receiptamt=@_amt
where cname = @_cn and (receiptdate < @_da or receiptdate='null')
If you need to do this for all customers, it will be a lot faster to truncate the table and insert everything in one go:
This asumes that the max. date is “unique” i.e. that not two rows with the same date exists in
accounts.If you really, really want to update the table each time something changes, you can use something like this:
The
customer_master.cname = 'some customer name'runs the update for a single customer, not for all. (I don’t know if that is going to work in MySQL though)Note that you do need to JOIN on the group by statement in order to get the correct amount that “belongs” to the latest receiptdate.
If you use a simple
the returned max. amount does not necessarily “belong” to the max. date (it could be an amount from a different date).