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 | | aaa@test.com |
+----+------+-------+--------------+
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 | aaa@test.com |
+----+------+-------+--------------+
Thanks in advance!
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.