7

我想这样做

  • 获取名为 table 的 blogs 中的所有行。
  • 将它们复制到临时数据库中
  • 编辑这个临时表记录的语言字段
  • 插入博客表

我正在尝试这样:

CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
INSERT INTO blogs SELECT * FROM tmptable; dump database tmptable;

但是我得到重复的密钥错误......

我该如何预防?

-编辑-

我试过了:

CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
ALTER TABLE tmptable DROP id;
INSERT INTO blogs SELECT * FROM tmptable; dump database tmptable;

但随后Column count doesn't match value count at row 1

-编辑-

我相信这会奏效(它确实有效,因为我知道存在多少记录)

CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
UPDATE tmptable SET id = id + 1000;
INSERT INTO blogs SELECT * FROM tmptable;

但我怎样才能正确地做到这一点?(只需为主键(id)设置下一个可用的自动增量值(没有 PHP/alike))

-编辑-

也许是这样的???

CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
UPDATE tmptable SET id = id + (SELECT id FROM blogs ORDER BY id DESC LIMIT 1);
INSERT INTO blogs SELECT * FROM tmptable;
4

5 回答 5

17

不需要临时表。

INSERT INTO blogs (lan, col1, col2, col3, ...)
SELECT 1, col1, col2, col3, ...
FROM blogs
WHERE lan = 2

替换为除和col1, col2, col3, ...之外的所有列的列表。lanid

于 2013-05-09T19:12:28.357 回答
4
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
alter table tmptable drop column id;
INSERT INTO blogs SELECT NULL,tmptable.* FROM tmptable;

假设,列“id”是第一个列。

于 2013-05-11T23:04:07.353 回答
1
UPDATE blogs SET lan = 1 WHERE lan = 2;

只需在原始表上运行该查询。

我不想更改语言,我想保存所有记录的另一个副本并指定此副本另一种语言

在这种情况下,请从临时表中删除主键。插入行时,不要包含主键列:

INSERT INTO blogs (title, lan) SELECT * FROM tmptable;
于 2013-05-09T18:45:12.543 回答
1

请尝试以下sql。一个类似的 SQL FIDDLE

 CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
    UPDATE tmptable SET lan = 1;
    UPDATE tmptable SET id = (select @val:=@val+1 from(select @val:=(select max(id) from blogs)) t)
    INSERT INTO blogs SELECT * FROM tmptable;

希望这可以帮助。

于 2013-05-16T06:34:54.807 回答
0

使用准备好的语句,您可以查询要使用的列的信息架构,然后伪造您要执行的查询:

这是您的案例的示例:

-- first query all the blogs column minus id and lan

SELECT GROUP_CONCAT(c.COLUMN_NAME)
INTO @cols
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE
 c.TABLE_NAME = 'blogs'
 AND c.COLUMN_NAME not in ('id', 'lan');

-- second build the query with the gathered columns
-- like INSERT INTO blogs(lan, col1, ...) SELECT 2, col1, ... FROM blogs WHERE lan=1

SET @sql=CONCAT(CONCAT(CONCAT(CONCAT('INSERT INTO blogs (lan,', @cols), 
                ') SELECT 2,'), @cols), ' FROM blogs WHERE lan=1');

-- prepare the statement    
PREPARE stmt FROM @sql;

-- and last run the insert
EXECUTE stmt;
于 2013-05-15T12:05:32.357 回答