MySQL Query将行插入到列中没有特定值的表中

时间:2014-05-05 07:40:18

标签: mysql sql

我有以下查询生成下面的结果表

select i.invoice_date,i.invoice_number,i.invoice_subtotal,p.payment from
invoice i
inner join payments p
on i.invoice_number = p.invoiceGRN_id
where i.payment_type = 'Credit'

enter image description here

我需要做的是,

  • 为每个invoice_number插入一行以及相关的行 invoice_subtotal(invoice_subtotal)与特定的相同 INVOICE_NUMBER,
  • 如果特定invoice_number没有,则
  • 支付= 0.0 已经有一个付款= 0.0
  • 的记录

请帮助我。

1 个答案:

答案 0 :(得分:0)

我假设您要插入2个表格(发票和付款),您需要一个包含以下2个查询的程序,

insert into invoice(invoice_date, invoice_number, invoice_subtotal,...) 
select invoice_date, invoice_number, invoice_subtotal,... from invoice i1 where i1.payment_type = 'Credit' and not exists(select * from payments p1 where i1.invoice_number = p1.invoiceGRN_id and p1.payment = 0.0);

insert into payments(invoiceGRN_id, payment, ...)
select invoiceGRN_id, payment,... from payments p1 where p1.invoiceGRN_id not in (select invoiceGRN_id from payments p2 where p2.payment=0.0);