tags:

views:

40

answers:

2

I have two tables invoices and pending_payments both of which have the following rows in common: invoice_id and balance. I want to do a select in MySQL that'll work thus:

[pseudo-code]

if(invoice_id exists in pending_payments table) {
    select balance from pending_payments where invoice_id = yadayadayada
} else {
    select balance from invoices where invoice_id = yadayadayada
}

Is this even doable in MySQL? If so, how?

+4  A: 
select i.invoice_id, coalesce(pp.balance, i.balance) as Balance
from invoices i
left outer join pending_payments pp on i.invoice_id = pp.invoice_id

Let me know if there can be multiple rows in pending_payments for the same invoice_id and I will propose an alternate solution.

RedFilter
Wow, thanks OrbMan that was quick! Will give it shot in a bit and let you know how it works.
freakwincy
No, the invoice_id is unique and your solution worked, beautifully. Thanks! It appears you made a slight mistake though- the first value after the coalesce statement should be pp.balance. Not a criticism, mind you just a pointer to anyone else who might've run into a similar problem.
freakwincy
Thanks, I fixed the typo.
RedFilter
+1  A: 

I like OrbMan's solution (I think it is the most intuitive), but here is another way -- select all from one table and then the ones that you have not selected from the 2nd.

select invoice_id, balance from pending_payments where invoice_id = yadayadayada
UNION
select invoice_id, balance from invoices where invoice_id = yadayadayada
  AND invoice_id not in (select invoice_id from pending_payments)

and as a side note, some have stated that on some systems this is actually faster. I make no such claims, but if speed is an issue it is worth trying.

Also, if you need to include a source column (eg pending or invoice) it is easy to do it this way like this:

select 'pending' as source, invoice_id, balance from pending_payments where invoice_id = yadayadayada
UNION
select 'invoice' as source, invoice_id, balance from invoices where invoice_id = yadayadayada
  AND invoice_id not in (select invoice_id from pending_payments)
Hogan
Much appreciated Hogan. Your solution is elegant in its simplicity. I tried it out too (without the source column as I didn't need it) just to make sure that it worked- and it did!
freakwincy
You're welcome. It is always good to know more than one way to do things (and in SQL there always is more than one way to do something.)
Hogan