【问题标题】:How to rename the column data to unique strings to add unique constraints on column using unix timestamp?如何将列数据重命名为唯一字符串以使用 unix 时间戳对列添加唯一约束?
【发布时间】:2018-07-31 16:29:59
【问题描述】:

我有类似的表结构 用户表
编号 |名称
1 |约翰
2 |山姆
3 |约翰
4 |山姆
5 |约翰

现在我想在表的 name 列上添加唯一键约束,并通过附加时间戳来更新这些值,所以我的输出应该像

标识 |名称
1 |约翰
2 |山姆
3 |约翰1533051839
4 |山姆1533051840
5 |约翰1533051841

我正在尝试使用临时表来做到这一点?我能做到吗? 我正在尝试以下解决方案

drop table if exists temp_user;

create table temp_user(id int(20), name varchar(128));

insert into temp_user
  select id, name
  from user
  group by user.name;


update user u
  inner join temp_user temp_u ON temp_u.id = u.id
  SET u.name = CONCAT(u.name, UNIX_TIMESTAMP());


drop table temp_user;

【问题讨论】:

  • 什么数据库平台,你的解决方案有什么问题?你不说有没有错误或者别的什么。
  • 我正在使用 MySQL,当我执行此操作时,我最终会用相同的字符串重命名所有名称。

标签: sql unique


【解决方案1】:

如果我已经了解您想要什么,您需要在 Name 中添加时间戳以使其唯一。也许这不能完全回答你的问题,但我有一个提示。为此,您应该使用触发器而不是创建索引或编写更复杂的查询,其优点如下:

  1. 索引很难维护,因此只有当索引属性涉及频繁查询或显着降低表的基数的 where 子句时,才应考虑使用索引。
  2. 如果您必须编写更复杂的查询,它可能无法在其他应用程序中使用,假设您有一个带有表单的 Web 应用程序,用户可能想要插入他或她的姓名而不是时间戳。

显然触发器语法取决于您的 dbms,但举个例子说明您可以在 Oracle 中做什么:

 create or replace trigger updateName
 after insert on user_table

 declare
 number_of_user int;

 begin

 select count(*) into number_of_user
 where Name = :NEW.Name;

 if(number_of_user <> 0) then
    :NEW.Name = CONCAT(:NEW.Name, UNIX_TIMESTAMP());
 end if;
 end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2013-05-11
    • 1970-01-01
    相关资源
    最近更新 更多