2013-12-13 88 views
0

我有以下查詢:mysql的最大嚴格模式

DELETE FROM table1 
WHERE node_id = ".$id." 
AND date < (
      SELECT 
       (MAX(date)- INTERVAL 1 MONTH) 
      from table1 
      WHERE node_id = ".$id." 
) 

然而,由於被啓用的MySQL嚴格的模式我的錯誤:

ERROR 1093 (HY000): You can't specify target table 'table1' for update in FROM clause 

調查後在線我試圖重新作爲查詢如下:

SELECT 
    * 
FROM table1 as tb1 
INNER JOIN table1 as tb2 
    on tb1.id = tb2.id 
HAVING tb1.date < MAX(tb2.date)-INTERVAL 1 MONTH AND tb1.node_id = 1; 

但是結果集返回空。

我已將max(tb2.date)更改爲手動輸入的日期,這給了我期待的結果。

任何想法發生了什麼?

+0

嘗試使用alice名稱表 – bgs

+0

誰!!「£%是愛麗絲? – Strawberry

回答

0

你可以試試嗎?

使用JOIN

數據

mysql> select * from test; 
+---------+------------+ 
| node_id | dt   | 
+---------+------------+ 
|  1 | 2011-03-01 | 
|  1 | 2011-02-01 | 
|  1 | 2011-01-01 | 
+---------+------------+ 
3 rows in set (0.00 sec) 

SELECT

SELECT * 
FROM (
    SELECT MAX(dt) AS max_dt 
    FROM test 
    WHERE node_id = 1 
) x INNER JOIN test ON test.node_id = 1 AND test.dt < x.max_dt; 
+------------+---------+------------+ 
| max_dt  | node_id | dt   | 
+------------+---------+------------+ 
| 2011-03-01 |  1 | 2011-01-01 | 
| 2011-03-01 |  1 | 2011-02-01 | 
+------------+---------+------------+ 

DELETE

DELETE test 
FROM (
    SELECT MAX(dt) AS max_dt 
    FROM test 
    WHERE node_id = 1 
) x INNER JOIN test ON test.node_id = 1 AND test.dt < x.max_dt; 
Query OK, 2 rows affected (0.02 sec) 

檢查

mysql> select * from test; 
+---------+------------+ 
| node_id | dt   | 
+---------+------------+ 
|  1 | 2011-03-01 | 
+---------+------------+ 
1 row in set (0.00 sec) 

使用變量

在你的情況,你正在試圖刪除只有一個NODE_ID。這使得簡單的查詢。

SELECT @max_dt := MAX(dt) 
FROM test 
WHERE node_id = 1; 
+--------------------+ 
| @max_dt := MAX(dt) | 
+--------------------+ 
| 2011-03-01   | 
+--------------------+ 


DELETE FROM test 
WHERE node_id = 1 
AND dt < @max_dt; 
Query OK, 2 rows affected (0.00 sec) 

BTW

你問17個問題,但沒有接受任何的答案。沒有有用的答案嗎?