Py学习  »  DATABASE

MySQL如何使用check?

eliesmith • 3 年前 • 377 次点击  

我是MYSQL的初学者,我正在尝试使用 CHECK 对于 EmployeeID 格式为 E### 其中“#”是数字(int)。还有 DOB 也就是说,从当前日期算起,Enterd应该是16岁或更大。这是表格的代码。谢谢你的帮助!

Create table Employee(
EmployeeID varchar(200) not null primary key,
DOB date, 

##Check (DOB <= CURRENT_DATE - interval '16' year),
FirstName varchar(200),
MiddleName varchar(200),
LastName varchar(200),
Address varchar(255),
StartDate date,
Gender varchar(100)
);
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130139
 
377 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Schwern
Reply   •   1 楼
Schwern    4 年前

Other answers covered using the check constraints .

然而,如果 总是 要以“E”开头,您需要存储“E”吗?你能存储整数,然后再加上E吗?整数主键更简单、更快、更小、更健壮。

使用 generated column 提供带有E的ID。

create table Employee (
  -- No check required, it's an integer by definition.
  -- Takes less storage to store and index.
  ID integer primary key,

  -- A generated virtual column (takes no storage space)
  EmployeeID varchar(255) as (concat('E', id)) virtual
);

insert into Employee (id) values (1), (23), (456);

select * from Employee;

ID      EmployeeID
1       E1
23      E23
456     E456

select * from Employee where EmployeeID = 'E456';

ID      EmployeeID
456     E456

Try it .

Will Walsh
Reply   •   2 楼
Will Walsh    4 年前

我会使用正则表达式来确认EmployeeID的有效性,例如:-

EmployeeID varchar(200) not null primary key CHECK EmployeeID REGEXP 'E\d{3}',