如何有条件地从两个表中选择一个字段?

时间:2010-04-15 14:10:19

标签: mysql select

我有两张桌子发票和pending_payments,它们都有以下共同的行:invoice_id和balance。我想在MySQL中做一个可以这样工作的选择:

[伪代码]

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
}

这在MySQL中是否可行?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:4)

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

如果同一pending_payments的{​​{1}}中有多行可以告诉我,我会提出另一种解决方法。

答案 1 :(得分:1)

我喜欢OrbMan的解决方案(我认为这是最直观的),但这是另一种方式 - 从一个表中选择所有表,然后从第二个表中选择那些表。

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)

作为附注,有些人表示在某些系统上这实际上更快。我没有提出这样的说法,但如果速度是一个问题,那么值得尝试。

此外,如果您需要包含源列(例如待处理或发票),则可以通过以下方式轻松完成:

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)