This article mainly explains the usage and meaning of mysql common functions, including string functions, numeric functions, date functions, and process functions.
1. String functions
① CONCAT(S1,S2,...,Sn): Concatenate S1 to Sn into a character string;
② LOWER(Str): Convert all strings Str to lowercase;
③ UPPER(Str): Convert the string Str to uppercase;
④ LPAD(Str,n,pad): Fill the left side of the string Str with the string pad to reach the length of n characters;
⑤ RPAD(Str,n,pad): Fill the right side of the string Str with the string pad to reach the length of n characters;
⑥ TRIM(Str): Remove the space at the head and tail of the character;
⑦ SUBSTRING(Str,Start,Len): Intercept the character string Str from Start to Len length.
2. Numeric functions
① CEIL(X): Round up;
② FLOOR(X): round down;
③ MOD(X,Y); returns the modulus of X/Y;
④ RAND(): returns a random number between 0 and 1;
⑤ ROUND(X,Y): Find the rounded value of X, and keep Y decimal places;
Example: Generate a 6-digit random verification code:
3. Date function
① CURDATE(): returns the current date;
② CURTIME(): returns the current time;
③ NOW(); returns the current date + time;
④ YEAR(date): Get the year of the specified date;
⑤ MONTH(date): Get the month of the specified date;
⑥ DAY(date): Get the number of days of the specified date;
⑦ DATE_add(date, INTERVEL expr type): returns the time value after a specified date/time date plus an expr value;
⑧ DATEDIFF(date1, date2): returns the number of days between two dates;
4. Process function
① IF(value, t, f): If the expression of value is true, return t, otherwise return;
② IFNULL(value1, value2): If value1 is not empty, return value1, otherwise return value2;
③ CASE WHEN [val1] THEN [res1]…ELSE [DEFAULT] END: If val1 is true, the return value is res1,… otherwise the return value is default; there are two tables, a student information table student
and a score table sc, the table is as follows , It is necessary to judge that the score greater than 80 is excellent, the score greater than 60 is pass, and the others are fail:
student table:
score table:
write the sql statement as follows:
select s.*, (case when sc.score>80 then '优秀' when sc.score>60 then '及格' else '不及格' end )as 'level' from student as s
left join sc on s.SId = sc.SId;
The execution result is:
④ CASE [expr] WHEN [val1] THEN [res1]...ELSE [defalut] END: If the value of expr is equal to val1, return res1, otherwise return the value defalut.