Reputation: 315
Suppose I have a table with 4 columns: ID (auto-increment), name, phone and e-mail. The problem is that sometimes the name is repeated. For example:
+----+------+-------+--------------+
| id | name | phone | email |
+----+------+-------+--------------+
| 1 | aaa | | |
| 2 | aaa | 123 | |
| 3 | aaa | | [email protected] |
+----+------+-------+--------------+
Which would be the best way to merge these 3 entries into one with all the fields present? The expected result would be:
+----+------+-------+--------------+
| id | name | phone | email |
+----+------+-------+--------------+
| 4 | aaa | 123 | [email protected] |
+----+------+-------+--------------+
Thanks in advance!
Upvotes: 1
Views: 34
Reputation: 1269803
You can do this using aggregation, except for the setting of the id
. Does this do what you want?
select max(id) + 1, name, max(phone) as phone, max(email) as email
from table t
group by name;
EDIT:
If you wanted to insert a new value and then delete the old ones, you could do:
insert into table(name, phone, email)
select max(id) + 1, name, max(phone) as phone, max(email) as email
from table t
group by name
having count(*) > 1;
And then:
delete t from table t join
(select t.name, max(id) as maxid
from table t
group by t.name
) tt
on t.name = tt.name and t.id < tt.maxid;
Upvotes: 2