在 MySql 中为不同用户存储相同的唯一编号

Store the same Unique Number for different users in MySql

我有一个员工 Table,它在 emp_no 列中存储唯一的员工编号。问题是,如果另一个用户或公司将其员工存储在同一个 table 中,并且有一个员工编号相同,例如1001 已经使用过的,他们不能在那里存储员工。
我想知道的是我应该为每个新用户创建一个新员工 table 还是有不同的解决方案?

不,不要创建多个员工table

你的情况在SQL世界里很标准,就是我们所说的1对N关系(或one to many)。一个公司可以有很多员工,但是一个员工关联一个公司。

您需要使用唯一的公司 ID 和公司名称创建公司 table。 然后,在您的员工 table 中,您将带有外键约束的新列添加到公司 ID 列。 最后,在您的员工 table 中,设置一对夫妇的唯一约束 (emp_no, company_id),以便唯一性约束代表您的现实世界约束。

Baxbong 的回答是正确的,但还不够深入。您应该像这样设置表格:

create table companies (
    company_id int auto_increment primary key,
    company_name varchar(255),
    . . .  -- all your other columns
);

create table employees (
    employee_id int auto_increment primary key,
    company_id int not null,
    emp_no varchar(255) not null,
    . . .  -- all your other columns
    constraint unq_employees_company_empno unique (company_id, emp_no),
    constraint fk_employees_company foreign key (company_id) references companies (company_id)
);

这里的要点是 employees 有一个主键列。这可以用于其他表中的外键引用。