2011-06-28 67 views
1

我試圖更新滿足以下條件的記錄日期列的條件更新表中的記錄:滿足相關同桌

  • 列站必須是一樣的站從有記錄FILTER_NR = X !
  • 和地位(11,12,13)
  • 和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 (...); 

回答

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爲當前日期,但請隨時隨意設置它你可能會喜歡的。

希望這會有所幫助!

+0

感謝您的回答,SQL語句正常工作! @Andomar的SQL也是正確的。給我一些時間來決定接受哪個答案。 –

2

你可以將ty是這樣的:

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 
     ) 
+0

乍一看,我認爲這應該工作,但MYSQL給了我錯誤:'錯誤1093(HY000):你不能指定目標表'過濾器'在FROM子句中更新' –

+0

正確的,那是因爲你可以' t更新並選擇同一個表 – Abhay

+0

@Christian Ammer:在另一個子查詢中重疊表格通常可以解決這個問題,編輯回答 – Andomar