我正在尝试从同一个tabl中的另一列更新列的值e-但是失败了“ERROR 1093(HY000):您无法在FROM子句中指定目标表'tab_1'进行更新”< / p>
我在Mysql中有什么
DT; date_custom
2012-10-31 17:00:22; 0
2012-09-31 17:00:21; 0
2012-07-31 17:00:25; 0
2012-10-31 17:43:56; 0
2012-11-31 17:44:09; 0
我在相应的date_custom字段(列)中需要什么
2012-10-31
2012-09-31
2012-07-31
2012-10-31
2012-11-31
换句话说,我只是希望Mysql为DT列选取相应的行,而只需要DUMP派生值date_column。这应该是一对一的。我确实有一个唯一标识行的键组合,但如果我能识别出来,我不想使用它。
以下是我尝试过但没有效果的内容。
Before this I created this column - date_custom as below -:
alter table tab_1
add column date_custom int not null;
# simplistic
UPDATE tab_1 SET date_custom = (SELECT SUBSTRING_INDEX(DT," " ,1) FROM tab_1);
我也知道我在尝试访问时无法同时修改列 - 但由于这是不同的列,所以事情不应该在这里失败,对 - 或者我做错了什么?
# using self joins on subquery
UPDATE tab_1
SET tab_1.date_custom =
(
SELECT SUBSTRING_INDEX(a.DT," " ,1)
FROM tab_1 a
INNER JOIN tab_1 b on
a.DT = b.DT and a.AUCTION_ID_64=b.AUCTION_ID_64 # these 2 columns together make up the primary key, but I would like to avoid using this if possible
) # does not work
这对应于此处的帖子You can't specify target table for update in FROM clause
**从官方文档 - “通常,您不能修改表并从子查询中的同一个表中进行选择。例如,此限制适用于以下形式的语句:”**
DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);
Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:
UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);
答案 0 :(得分:17)
使用SELF JOIN,如下所示:
UPDATE test t1, test t2
SET t1.date_custom = SUBSTRING_INDEX(t2.dt," " ,1)
WHERE t1.id = t2.id
答案 1 :(得分:3)
对接受的答案只做一点修改:
使用大表格SELF JOIN
可能需要花费大量时间来处理
您可以使用不UPDATE
SELF JOIN
UPDATE test t1
SET t1.date_custom = SUBSTRING_INDEX(t1.dt," " ,1);
改善DRASTICALLY的表现
使用SELF JOIN
测试了类似的查询26000行还没有在两小时内完成(想象一个有milions条目!!!)但没有SELF JOIN
相同的查询需要不到2秒