更新从同一Query中的SELECT检索的结果

时间:2014-05-02 09:38:32

标签: mysql sql

我需要更新"付款"表" payment_status"列到' 1'在结果中跟随SELECT查询但在单个查询中。请帮帮我。

SELECT * FROM payments p
INNER JOIN invoice i
ON i.invoice_number = p.invoiceGRN_id
WHERE i.invoice_status = '2' AND i.payment_type = 'Credit'

2 个答案:

答案 0 :(得分:5)

您可以使用UPDATE

进行INNER JOIN
UPDATE payments p
INNER JOIN invoice i
ON i.invoice_number = p.invoiceGRN_id
SET p.payment_status = 1
WHERE i.invoice_status = '2' AND i.payment_type = 'Credit'

或者你可以做这样的事情(效率较低,但更直接地回答你的问题):

UPDATE payments 
SET payment_status = 1 
WHERE id IN (
    SELECT p.id FROM payments p
    INNER JOIN invoice i
    ON i.invoice_number = p.invoiceGRN_id
    WHERE i.invoice_status = '2' AND i.payment_type = 'Credit'
)

答案 1 :(得分:1)

这应该可以解决问题:

UPDATE payments SET payment_status = 1 WHERE payment_ID in (
  SELECT payment_ID FROM payments p
  INNER JOIN invoice i
  ON i.invoice_number = p.invoiceGRN_id
  WHERE i.invoice_status = '2' AND i.payment_type = 'Credit')