Technology Sharing

MySQL conditional function/encryption function/conversion function

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Conditional Function

  • IF(): If a condition is true, return one value, otherwise return another value.
  1. -- 示例:根据员工的薪水返回薪水等级
  2. SELECT name, salary,
  3. IF(salary < 3000, 'Low',
  4. IF(salary BETWEEN 3000 AND 7000, 'Medium', 'High')) AS salary_level
  5. FROM employees;
  • CASE: More complex conditional logic, similar to switch-case statements in programming languages.
  1. SELECT
  2. CASE
  3. WHEN score >= 90 THEN 'A'
  4. WHEN score >= 80 THEN 'B'
  5. WHEN score >= 70 THEN 'C'
  6. WHEN score >= 60 THEN 'D'
  7. ELSE 'F'
  8. END AS grade
  9. FROM students;
  • COALESCE(): Returns the first non-NULL value in the parameter list.
  1. SELECT name, COALESCE(city, 'Unknown') AS city
  2. FROM students;

Encryption Function

  • MD5(): Calculates the MD5 hash value of a string.
  1. -- 示例:对用户的密码进行MD5加密
  2. SELECT MD5('password123') AS encrypted_password;
  • SHA1(): Calculates the SHA-1 hash value of a string.
SELECT SHA1('7895656')

Conversion functions

  • CAST(): Converts an expression to a specified data type.
  1. -- 示例:将字符串转换为整数
  2. SELECT CAST('123' AS UNSIGNED) AS number;
  • CONVERT(): The function is similar to CAST() and is used for type conversion.
  1. -- 示例:将日期字符串转换为日期类型
  2. SELECT CONVERT('2023-01-01', DATE) AS converted_date;