[英]MySQL - Merge rows in table based on multiple criteria
I'd like to merge rows based on multiple criteria, essentially removing duplicates where I get to define what "duplicate" means. 我想根据多个条件合并行,从本质上讲,在我定义“重复”的含义的地方删除了重复项。 Here is an example table: 这是一个示例表:
╔═════╦═══════╦═════╦═══════╗
║ id* ║ name ║ age ║ grade ║
╠═════╬═══════╬═════╬═══════╣
║ 1 ║ John ║ 11 ║ 5 ║
║ 2 ║ John ║ 11 ║ 5 ║
║ 3 ║ John ║ 11 ║ 6 ║
║ 4 ║ Sam ║ 14 ║ 7 ║
║ 5 ║ Sam ║ 14 ║ 7 ║
╚═════╩═══════╩═════╩═══════╝
In my example, let's say I want to merge on name
and age
but ignore grade
. 在我的示例中,假设我想按name
和age
合并,但忽略grade
。 The result should be: 结果应为:
╔═════╦═══════╦═════╦═══════╗
║ id* ║ name ║ age ║ grade ║
╠═════╬═══════╬═════╬═══════╣
║ 1 ║ John ║ 11 ║ 5 ║
║ 3 ║ John ║ 11 ║ 6 ║
║ 4 ║ Sam ║ 14 ║ 7 ║
╚═════╩═══════╩═════╩═══════╝
I don't particularly care if the id
column is updated to be incremental, but I suppose that would be nice. 我不太在意id
列是否更新为增量,但是我想那会很好。
Can I do this in MySQL? 我可以在MySQL中这样做吗?
My suggestion, based on my above comment. 根据以上评论,我的建议。
SELECT distinct name, age, grade
into tempTable
from theTable
This will ignore the IDs and give you only a distinct dump, and into a new table. 这将忽略ID,仅给您一个不同的转储,并进入一个新表。
Then you can either drop the old and, and rename the new one. 然后,您可以删除旧的,然后重命名新的。 Or truncate the old one, and dump this back in. 或截断旧的,然后倒回去。
You could just delete the duplicates in place like this: 您可以像这样删除重复项:
delete test
from test
inner join (
select name, age, grade, min(id) as minid, count(*)
from test
group by name, age, grade
having count(*) > 1
) main on test.id = main.minid;
Example: http://sqlfiddle.com/#!9/f1a38/1 示例: http : //sqlfiddle.com/#!9 / f1a38 / 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.