我已经使用mysql名称创建了具有六个属性id,name,lastname,dob(存储在Date数据类型中),性别,城市的人,并且我希望该值在dob(出生日期)中输入大于18 。我如何设置此约束,请帮忙
MySQL does not support check constraints. So, the only way to do this in MySQL is to create a trigger or wrap the insert in a stored procedure.
The specific logic that you would use is:
dob <= curdate() - interval 18 year
So, in almost any other database, this would look something like:
alter table t add constraint chk_t_dob check (dob <= curdate() - interval '18' year);
(Note: date operations vary among databases.)
Consider the following, on this the 24th June 2017...
CREATE TABLE dobs(dob DATE NOT NULL);
INSERT INTO dobs (dob)
SELECT '2012-01-01' x FROM (SELECT 1) a WHERE FLOOR(DATEDIFF(NOW(),'2012-01-01') / 365.24) >= 18;
INSERT INTO dobs (dob)
SELECT '1975-01-01' x FROM (SELECT 1) a WHERE FLOOR(DATEDIFF(NOW(),'1975-01-01') / 365.24) >= 18;
INSERT INTO dobs (dob)
SELECT '1999-06-25' x FROM (SELECT 1) a WHERE FLOOR(DATEDIFF(NOW(),'1999-06-25') / 365.24) >= 18;
INSERT INTO dobs (dob)
SELECT '1999-06-24' x FROM (SELECT 1) a WHERE FLOOR(DATEDIFF(NOW(),'1999-06-24') / 365.24) >= 18;
SELECT * FROM dobs;
+------------+
| dob |
+------------+
| 1975-01-01 |
| 1999-06-24 |
+------------+
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.