gpt4 book ai didi

mysql - 使用 mysql 中另一列的派生值更新列

转载 作者:IT老高 更新时间:2023-10-29 00:20:14 24 4
gpt4 key购买 nike

我正在尝试从同一个表中的另一列更新一列的值,但这失败了“错误 1093 (HY000):您无法在 FROM 子句中指定目标表‘tab_1’进行更新”

我在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 ...);

最佳答案

使用 SELF JOIN,如下所示:

UPDATE test t1, test t2 
SET t1.date_custom = SUBSTRING_INDEX(t2.dt," " ,1)
WHERE t1.id = t2.id

工作演示:http://sqlfiddle.com/#!2/9b71cb/1/0

关于mysql - 使用 mysql 中另一列的派生值更新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21227445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com