Now I want to calculate Age in Student table .I want to insert student record only greater then 18 year old .
mysql >alter table student add column Age double (18,2) check (Age >=18);
Action Output: 0 row(s) affected Records: 0 Duplicates: 0 Warnings: 0 0.066 sec
mysql > select * from student;
Action Output:
# ID, DOB, STUDENT_NAME, gender_id , Age
'1', '2020-01-01', 'A', '1' , NULL
Solution 1 :
Now update Age in Student table :
CREATE TABLE `student` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DOB` date DEFAULT NULL,
`STUDENT_NAME` varchar(10) DEFAULT NULL,
`gender_id` int(11) DEFAULT NULL,
`Age` int(11) DEFAULT NULL, `CHECK` ( AGE >=18 ),
PRIMARY KEY (`ID`),
UNIQUE KEY `IDDOB` (`ID`,`DOB`),
KEY `fk_gender_id` (`gender_id`),
CONSTRAINT `fk_gender_id` FOREIGN KEY (`gender_id`) REFERENCES `gender` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Year Count :
mysql >set @dob='2000-01-01'
select year(now())-year(@dob);
Output: 20
mysql >set @dob='2000-01-01'
select date_format(from_days(datediff(now(),@dob)),'%Y')+ 0 ;
Output# date_format(from_days(datediff(now(),@dob)),'%Y')+ 0
'20'
No comments:
Post a Comment