我有一个包含表myTable
和列id, NameID, InvoiceNo, BilleeNo, Date
的MySQL数据库。行数不断变化(可能会增加或减少)。
myTable的:
id NameID InvoiceNo BilleeNo Date
1 N01 4566 02 01-MAR-2013
2 N01 unallocated 02 01-MAR-2013
3 N02 1233 02 01-MAR-2013
4 N02 1233 02 01-MAR-2013
5 N02 unallocated 02 01-MAR-2013
6 N02 1244 02 01-JUN-2013
我想更新未分配的InvoiceNo
,InvoiceNo
具有相同的NameID, BilleeNo
和Date
。
更新后的表格为:
id NameID InvoiceNo BilleeNo Date
1 N01 4566 02 01-MAR-2013
2 N01 4566 02 01-MAR-2013
3 N02 1233 02 01-MAR-2013
4 N02 1233 02 01-MAR-2013
5 N02 1233 02 01-MAR-2013
6 N02 1244 02 01-JUN-2013
我尝试了这个查询:
UPDATE np as updated_np
SET invoice_no = old_np.invoice_no
FROM np as old_np
WHERE old_np.nameid = updated_np.nameid and
old_np.date = updated_np.date and
old_np.BILLEE_NO = updated_np.BILLEE_NO and
old_np.invoice_no != 'unallocated' and
updated_np.invoice_no='unallocated';
答案 0 :(得分:0)
您可以使用NameID(+其他列)在同一个表上加入,并在join子句中指定仅加入已经分配了InvoiceNo的数据集。
UPDATE myTable
INNER JOIN myTable AS upd
ON upd.NameID = myTable.NameID
AND upd.BilleeNo = myTable.BilleeNo
AND upd.Date = myTable.Date
AND upd.InvoiceNo != "unallocated"
SET
myTable.InvoiceNo = upd.InvoiceNo
WHERE
myTable.InvoiceNo = "unallocated"
答案 1 :(得分:0)
试试这个
update mytable set InvoiceNo='1233' where id in (select tb1.id from mytable tb1, mytable tb2 where tb1.InvoiceNumber='unallocated' and tb1.NameId=tb2.NameId and tb1.BilleNo=tb2.BilleNo and tb1.Date=tb2.Date)