我有这些表格:
customer:
customer_id vat_number
=========== ==========
1 ES-0000001
2 ES-0000002
3 ES-0000003
invoice:
invoice_id customer_id vat_number
========== =========== ==========
100 1 NULL
101 3 NULL
102 3 NULL
103 2 NULL
104 3 NULL
105 1 NULL
我想使用invoice.vat_number
的当前值填充customer.vat_number
处的NULL值。是否可以使用单个SQL语句执行此操作?
我到目前为止触发了语法错误:
UPDATE invoice
SET vat_number=cu.vat_number /* Syntax error around here */
FROM invoice iv
INNER JOIN customer cu ON iv.customer_id=cu.customer_id
WHERE invoice.invoice_id=iv.invoice_id;
答案 0 :(得分:4)
UPDATE invoice i, customer cu SET i.vat_number=cu.vat_number
WHERE i.customer_id = cu.customer_id;
你去吧
SET vat_number = cu.vat_number / *这里的语法错误* / 该错误是因为var_number列名称不明确 - MySQL不知道这是i.vat_number还是cu,vat_number。
答案 1 :(得分:4)
使用MySQL,ANSI-92 JOIN语法:
UPDATE INVOICE
JOIN CUSTOMER ON CUSTOMER.customer_id = INVOICE.customer_id
SET vat_number = CUSTOMER.vat_number
WHERE INVOICE.vat_number IS NULL
使用MySQL,ANSI-89 JOIN语法:
UPDATE INVOICE, CUSTOMER
SET INVOICE.vat_number = CUSTOMER.vat_number
WHERE CUSTOMER.customer_id = INVOICE.customer_id
AND INVOICE.vat_number IS NULL
more info, see the MySQL UPDATE documentation。这是MySQL特定的UPDATE语句语法,不太可能在其他数据库上受支持。
答案 2 :(得分:3)
类似的东西:
UPDATE invoice in
SET vat_number=(SELECT cu.vat_number FROM customer cu
WHERE in.customer_id=cu.customer_id)
-- not tested
答案 3 :(得分:0)
UPDATE iv
SET iv.vat_number=cu.vat_number
FROM invoice iv
INNER JOIN customer cu ON iv.customer_id=cu.customer_id