开发者

Removing duplicates of certain field

开发者 https://www.devze.com 2023-02-28 12:08 出处:网络
I have table looking as follows: Field| Type| Null| Key| Default | Extra ----------+--------------+---------+--------+---------+----------------

I have table looking as follows:

Field     | Type         | Null    | Key    | Default | Extra
----------+--------------+---------+--------+---------+----------------
index     开发者_StackOverflow| int(11)      | NO      | PRI    | NULL    | auto_increment
itemid    | int(11)      | NO      |        | NULL    |
name      | varchar(32)  | NO      |        | NULL    |
meta      | int(11)      | NO      |        | NULL    |

Table is small and I don't have to care about optimalisation.

Some of records have itemid, name, and meta duplicated but I want to remove all of those that have name duplicated, leaving one record (that is no longer duplicated.) This is MySQL. I searched for the solution but I found nothing that I cound make suit my needs.


Since the data is small it could be simpler to create a table with similar structure and perform such query:

INSERT INTO new_table (index, itemid, name, meta)
SELECT index, itemid, name, meta FROM old_table GROUP BY name

After that delete old_table and rename new_table.

Also the solution that could work (I'm not sure) would be to create an unique index with IGNORE, like

ALTER IGNORE TABLE tblname
ADD UNIQUE INDEX ix_name (name)

IGNORE is a MySQL extension to standard SQL. It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only the first row is used of rows with duplicates on a unique key, The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.


Not sure if its what you are looking for but you could try the GROUP BY clause

SELECT index, itemid, name, meta FROM table GROUP BY name
0

精彩评论

暂无评论...
验证码 换一张
取 消