MySql - 使用同一个表中的select语句更新表

时间:2012-05-01 18:56:21

标签: mysql

我正在尝试使用同一个表中不同行(和不同列)的值来更新表中的行。虽然我的语法没有产生任何结果:这是代码(更新):

UPDATE table1 AS t1 INNER JOIN
(SELECT field_id_46,field_id_47 FROM table1 WHERE entry_id = 36) AS t2
SET t1.field_id_60 = t2.field_id_46, t1.field_id_61 = t2.field_id_47
WHERE t1.entry_id = 45;

5 个答案:

答案 0 :(得分:47)

update table as t1
inner join (
select field_id_46,field_id_47 from table where entry_id = 36) as t2
set t1.field_id_60 = t2.field_id_46,
    t1.field_id_61 = t2.field_id_47
where t1.entry_id = 45

或简单地

update table as t1,
(
select field_id_46,field_id_47 from table where entry_id = 36) as t2
set t1.field_id_60 = t2.field_id_46,
    t1.field_id_61 = t2.field_id_47
where t1.entry_id = 45

答案 1 :(得分:9)

添加..

相同的表格,包含更多的一个寄存器

UPDATE table t1
INNER JOIN table t2 ON t2.entry_id = t1.entry_id
SET t1.field_id_60 = t2.field_id_60,
    t1.field_id_61 = t2.field_id_61

答案 2 :(得分:5)

您可以使用内部联接进行更新,如下所示:

UPDATE table1 AS t1 
    INNER JOIN table1 AS t2 
    SET t1.field_id_60 = t2.field_id_46, 
        t1.field_id_61 = t2.field_id_47 
WHERE t1.entry_id = 54;

答案 3 :(得分:0)

我发现这个问题非常有用,因为我试图在该特定数据库使用hibernate_sequence表时手动插入表中。 我使用这个问题的解决方案来修改我的导入脚本。 我有一个脚本,一个接一个地插入许多“插入”语句,我不得不手动设置id。例如:

insert into T01_REGIONS (ID, NAME) VALUES ({the next id from hibernate_sequence}, 'name1');
insert into T01_REGIONS (ID, NAME) VALUES ({the next id from hibernate_sequence}, 'name2');
..
.

所以我做的是以下方法来解决我的问题:

insert into T01_REGIONS (ID, NAME) VALUES ((select next_val from hibernate_sequence limit 1), 'name1');update hibernate_sequence as t1, (select next_val+1 as next from hibernate_sequence limit 1) as t2 set t1.next_val = t2.next;
insert into T01_REGIONS (ID, NAME) VALUES ((select next_val from hibernate_sequence limit 1), 'name2');update hibernate_sequence as t1, (select next_val+1 as next from hibernate_sequence limit 1) as t2 set t1.next_val = t2.next;
..
.

使用notepad ++,在我的sql脚本的每一行末尾添加额外的查询很容易。我知道这可能非常难看,但它确实对我有用,以便将数据导入到测试hibernate操作的mysql数据库,而我的数据来自oracle hibernate操作数据库。

答案 4 :(得分:-1)

您不需要此查询

SELECT field_id_46,field_id_47 FROM table WHERE entry_id = '36'

你应该这样做:

UPDATE table SET (field_id_60,field_id_61) ('coming_value','other_value') WHERE entry_id = '45';

你也可以用2种不同的颜色来做这件事。我想你可以这样做。但是我可能没有任何想法。你应该拆分这个查询用你使用的语言。在第一种方法你应该使用这个查询

SELECT field_id_46,field_id_47 FROM table WHERE entry_id = '36'

并且您还可以返回来自此数据的String。然后您可以在更新函数中使用此返回值。

相关问题