我正在尝试将行从tableA
复制到空白tableB
。
tableA
有一列mytext
,这些行与此列有重复。
问题
如何从A复制到B,而mytext
没有重复的行?换句话说,如果mytext
中有2个或更多行具有相同的值,请保留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
答案 0 :(得分: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)
答案 1 :(得分:2)
您可以使用GROUP BY mytext
将重复的行组合在一起。以下应该有效:
INSERT INTO tableB
SELECT * FROM tableA
WHERE id IN (SELECT MIN(id) FROM tableA GROUP BY mytext)