更新满足与同一表相关的条件的表记录

时间:2011-06-28 10:47:28

标签: mysql sql sql-update

我正在尝试更新满足以下条件的记录的日期列:

  • 列STATION必须与来自FILTER_NR = x
  • 的记录的STATION相同
  • AND STATUS IN(11,12,13)
  • AND FILTER_NR!= x

如果x = 3 UPDATE语句,我正在寻找,应该更改表FILTER:

+-----------+------------+---------+---------+
| FILTER_NR | PROBEDATE  | STATION |  STATUS |
+-----------+------------+---------+---------+
|         1 | 2011-06-01 |       1 |      10 |
|         2 | 2011-06-02 |       1 |      11 |
|         3 | 2011-06-03 |       1 |      12 |
|         4 | 2011-06-04 |       2 |      13 |
+-----------+------------+---------+---------+

为:

+-----------+------------+---------+----------+
| FILTER_NR | PROBEDATE  | STATION |  STATUS  |
+-----------+------------+---------+----------+
|         1 | 2011-06-01 |       1 |       10 | -> not changed
|         2 | 2011-06-01 |       1 |       11 | -> changed
|         3 | 2011-06-03 |       1 |       12 | -> not changed
|         4 | 2011-06-04 |       2 |       13 | -> not changed
+-----------+------------+---------+----------+

我开始关注SQL语句,你知道我怎么能完成它吗?

UPDATE FILTER SET PROBEDATE = ADDDATE(PROBEDATE, -1)
WHERE FILTER_NR IN (...);

2 个答案:

答案 0 :(得分:3)

这应该适合你:

UPDATE `FILTER` `F`
INNER JOIN `FILTER` `F1` ON `F1`.`FILTER_NR` = 3 AND `F1`.`STATION` = `F`.`STATION`
SET `F`.`PROBEDATE` = CURDATE()
WHERE `F`.`FILTER_NR` != 3
AND `F`.`STATUS` IN (11, 12, 13);

在我的示例中,我已将PROBEDATE设置为当前日期,但请随意将其设置为您可能喜欢的内容。

希望这有帮助!

答案 1 :(得分:2)

你可以这样:

UPDATE  FILTER 
SET     PROBEDATE = PROBEDATE - inteval 1 day
WHERE   STATUS IN (11,12,13)
        AND FILTER_NR != 3
        AND STATION IN
        (
        SELECT  STATION
        FROM    (
                SELECT  *
                FROM    FILTER
                ) as SubQueryAlias
        WHERE   FILTER_NR = 3
        )