高级SQL UPDATE问题

时间:2011-09-19 18:36:33

标签: mysql sql

我需要转换一个表格兑换,以包含一个将从blah填充的日期,但它现在不存在。

我需要选择兑换表中的所有行,其中pay autokey匹配redeem.pay。 blah.number包含在pay表中,而且我想得到blah.date。然后我需要将它设置为redeem.date并确保redeem.days_redeemed不等于0.

UPDATE redeem
SET redeem.date =(SELECT blah.date
FROM blah
INNER JOIN pay ON pay.number = blah.number
INNER JOIN redeem ON redeem.pay = pay.autokey
WHERE redeem.days_redeemed <>0)

这是我收到的错误:您无法在FROM子句

中指定目标表'redeem'进行更新

如何在一个SQL语句中在MySQL中执行此操作?

4 个答案:

答案 0 :(得分:2)

UPDATE
    redeem
  JOIN
    pay 
      ON pay.autokey = redeem.pay 
  JOIN
    blah
      ON blah.number = pay.number 
SET 
    redeem.date = blah.date
WHERE
    redeem.days_redeemed <> 0

这也应该有效:

UPDATE
    redeem
SET 
    date = 
      ( SELECT blah.date
        FROM 
            blah
          JOIN
            pay 
              ON blah.number = pay.number 
        WHERE 
            pay.autokey = redeem.pay 
      )
WHERE
    days_redeemed <> 0

答案 1 :(得分:1)

试试这个:

UPDATE redeem SET redeem.date = blah.date
FROM blah
INNER JOIN pay ON pay.number = blah.number
INNER JOIN redeem ON redeem.pay = pay.autokey
WHERE redeem.days_redeemed <>0

答案 2 :(得分:0)

如果你将它包装在另一个子查询中(因为MySQL发出子查询的方式)它应该有效:

UPDATE redeem
SET redeem.date =(SELECT date from ( select * from
FROM blah
INNER JOIN pay ON pay.number = blah.number
INNER JOIN redeem ON redeem.pay = pay.autokey
WHERE redeem.days_redeemed <>0))

答案 3 :(得分:0)

您应该在FROM子句中使用别名作为兑换表:

    UPDATE redeem
    SET redeem.date =(SELECT blah.date
    FROM blah
    INNER JOIN pay ON pay.number = blah.number
    INNER JOIN redeem r ON r.pay = pay.autokey
    WHERE r.days_redeemed <>0)