3

我正在尝试将行从复制tableA到空白tableB

tableA有一个列mytext,并且行有来自该列的重复项。

问题 如何从没有重复行的 A 复制到 B mytext?换句话说,如果 2 行或更多行具有相同的值,mytext则保留具有最低 id 号的行并复制到tableB.

最初我试图删除重复项但不断收到错误Error Code: 1205. Lock wait timeout exceeded from this sql command:

DELETE n1 
FROM tableA n1, tableA n2 
WHERE n1.id > n2.id 
AND n1.mytext = n2.mytext

我在amazons RDS

+---+-----+-----+------+-------+
|id |fname|lname|mytext|morevar|
|---|-----|-----|------|-------|
|   |     |     |      |       |
|   |     |     |      |       |
|   |     |     |      |       |
|   |     |     |      |       |
+------------------------------+ 
CREATE TABLE `tableB` (
    `id` int(11) NOT NULL,
    `fname` varchar(45) DEFAULT NULL,
    `lname` varchar(45) DEFAULT NULL,
    `mytext` mediumtext,
    `morevar` bigint(20) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

这不起作用,它没有捕获重复项,只是将所有值从 tableA 复制到 tableB

INSERT INTO tableB (`id`,`fname`,`lname`,`mytext`,`morevar`)
SELECT DISTINCT tableA.id,tableA.fname,tableA.lname,tableA.mytext,tableA.morevar
FROM tableA
4

2 回答 2

4

尝试这个

INSERT INTO tableB (`id`,`fname`,`lname`,`mytext`,`morevar`)
SELECT id, fname, lname, mytext, morevar
FROM tableA a
WHERE id = (Select Min(id) FROM tableA
            WHERE myText = a.mytext)

如果您需要分批执行此操作...(编辑 myText 标准以控制批次)

INSERT INTO tableB (`id`,`fname`,`lname`,`mytext`,`morevar`)
SELECT id, fname, lname, mytext, morevar
FROM tableA a
WHERE mytext < 'j'
   And id = (Select Min(id) FROM tableA
            WHERE myText = a.mytext)

INSERT INTO tableB (`id`,`fname`,`lname`,`mytext`,`morevar`)
SELECT id, fname, lname, mytext, morevar
FROM tableA a
WHERE mytext >= 'j'
   And mytext < 'r'
   And id = (Select Min(id) FROM tableA
            WHERE myText = a.mytext)

INSERT INTO tableB (`id`,`fname`,`lname`,`mytext`,`morevar`)
SELECT id, fname, lname, mytext, morevar
FROM tableA a
WHERE mytext >= 'r'
   And id = (Select Min(id) FROM tableA
            WHERE myText = a.mytext)
于 2013-06-28T02:50:18.750 回答
2

您可以使用 aGROUP BY mytext将重复的行组合在一起。以下应该有效:

INSERT INTO tableB
SELECT * FROM tableA
  WHERE id IN (SELECT MIN(id) FROM tableA GROUP BY mytext)
于 2013-06-28T03:01:14.007 回答