我的MySQL中有一个表有重复项。我尝试删除重复项并保留一个条目。我没有主键
我可以通过以下方式查找副本:
select user_id, server_id, count(*) as NumDuplicates
from user_server
group by user_id, server_id
having NumDuplicates > 1
但不能删除它们:
ALTER IGNORE TABLE `user_server`
ADD UNIQUE INDEX (`user_id`, `server_id`);
甚至SET foreign_key_checks = 0;不管用。 错误代码:1062。密钥'user_id_3'重复输入'142-20'
MySQL版本:5.5.18 引擎:InnoDB
还有其他方法吗?
答案 0 :(得分:9)
因为您使用了INNO DB,
一个简单的伎俩:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<span>Number of tickets @ $5/ticket:</span>
<input type="number" name="number-of-tickets" value="1" min="1" id="number-tickets" />
</label>
<label>
<span>Total amount:</span>
$ <input type="text" name="total-amount" value="" id="total-amount" readonly />
</label>
这样做
答案 1 :(得分:7)
可能最简单的方法是复制表的结构,将唯一索引添加到新表中然后执行:
INSERT IGNORE INTO new_table SELECT * FROM old_table
要删除重复项(每个项目除外)而不创建临时表,您可以这样做:
ALTER TABLE `user_server` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
DELETE us2 FROM user_server us1
JOIN user_server us2 USING (user_id, server_id)
WHERE us1.id < us2.id;
ALTER TABLE `user_server` DROP `id`;
答案 2 :(得分:0)
另一个解决方案,它保留user_server上的所有索引:
CREATE TABLE new_user_server LIKE user_server;
ALTER TABLE new_user_server ADD UNIQUE INDEX (`user_id`, `server_id`);
INSERT IGNORE INTO new_user_server SELECT * FROM user_server;
DROP TABLE user_server;
RENAME TABLE new_user_server TO user_server;