mysql最大严格模式

时间:2013-12-13 12:00:43

标签: mysql max mysql-error-1093

我有以下查询:

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)更改为手动输入的日期,这给了我期待的结果。

这里有什么想法?

1 个答案:

答案 0 :(得分: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 *
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 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)

顺便说一句

您提出了17个问题,但未接受任何答复。没有有用的答案吗?