如何用空白替换重复的列值而不删除MySql中的整行?

时间:2016-08-03 00:03:55

标签: mysql unique-key

我有mysql表格contacts,如下所示

id  |      email      |   mobile    |
1   | abc123@xyz.com  |  9800000023 | 
2   | abc123@xyz.com  |  9800000021 |
3   | pqr111@xyz.com  |  9800000034 |
4   | pqr123@xyz.com  |  9900000033 |
5   | abc111@xyz.com  |  9804400000 |
6   | pqr111@xyz.com  |  9800500000 |
7   | abc111@xyz.com  |  8600000000 |

我想将重复的电子邮件值(第一次出现除外)更新为null或空白而不影响mobile列。

解决方案应该看起来像

id  |      email      |   mobile    |
1   | abc123@xyz.com  |  9800000023 | 
2   |    <null>       |  9800000021 |
3   | pqr111@xyz.com  |  9800000034 |
4   | pqr123@xyz.com  |  9900000033 |
5   | abc111@xyz.com  |  9804400000 |
6   |    <null>       |  9800500000 |
7   |    <null>       |  8600000000 |

是否有办法IGNORE重复电子邮件列值,但应将mobile值插入表中。

1 个答案:

答案 0 :(得分:1)

update contacts
set email = null
where id not in
(
   select * from
   (
      select min(id)
      from contacts
      group by email
   ) tmp
)