Basic Queries — Built-in Functions

overview

1. Function overview
  • A program or code that can be directly called by a program at the other end.
  • Encapsulate a set of functional logic in the function body and expose the function name to the outside.
2. Advantages and disadvantages of functions
  • advantage:

    • Code implementation details are hidden.
    • Improved code reusability and simplicity.
  • Disadvantages: Poor portability, functions with similar functions may have different function names in different DBMSs

3. Classification of built-in functions
  • One-line functions: string functions, numeric functions, date functions, message functions, control functions...
  • Multi-row functions: aggregate functions.
4. Basic Grammar
select 函数名(实参列表) [from 表名];

Common one-line functions

1. String functions
  • Length function: length,char_length

    • lengthGet the number of bytes, char_lengthget the number of characters.

    • select length('张三'); # 6
      select char_lebgth('张三'); # 2
      
  • Splicing function:concat

    • Used to splice strings, you can specify what splicing

    • # 直接连接
      select concat(first_name, last_name) as fillname
      from employees;
      
      # 以'-'连接
      select concat(first_name, '-', last_name) as fillname
      from employees;
      
  • Case conversion: upper,lower

    • upperConvert all to uppercase and lowerall to lowercase.

    • select upper("Hello World"); # HELLO WORLD
      select lower("Hello World"); # hello world
      
  • Operand substring: substr,instr

    • substr: Take a substring, the index starts from 1

      # 截取从指定索引处后面所有字符
      select substr('good good study', 7); # ood study
      # 截取从指定索引处指定字符长度的字符
      select substr('day day up', 2, 5); # ay da
      
    • instr: Get the position where the substring appears and return the index of the first occurrence of the substring, if not found, return 0

      select instr('good good study', "good"); # 1
      select instr('good good study', "day"); # 0
      
  • Remove extra spaces and pad to the specified length: trim, lpad,rpad

    • trim: Remove extra spaces, or certain characters (first or last).

      select trim("siu     "); # siu
      select trim('~' from "~~~siu~~~~~ "); # siu~~~~~ 
      
    • lpadleft padding, rpadright padding

      select lpad('batman', 10, '*'); # ****batman
      select rpad('batman', 10, '*'); # batman****
      
  • replace:replace

    • replace some strings with others

    • select 'hello world' as "before", # hello world
      replace('hello world', 'world', 'mysql') as "after"; # hello mysql
      
2. Mathematical functions
  • Rounding and Rounding: round, ceil,floor

    • roundrounding

      select round(2.5); # 3
      select round(2.4);# 2
      
    • ceilround up, floorround down

      select ceil(2.6); # 3
      select floor(2.6); # 2
      
  • Truncated:truncate

    • Achieve the effect of retaining the required number of decimal places

    • select truncate(3.1415926, 2); # 3.14
      select truncate(3.1415926, 5); # 3.14159
      
  • Absolute value and random number: abs(),rand()

    • abstake the absolute value

      select abs(-1.414); # 1.414
      
    • randtake random number

      select rand(); # 任意随机数
      select round(rand() * 10); # 1~10的随机数
      
3. Date function
  • Get the current date and time

    • now: Returns the current system date and time.
    • curdate: Returns the current system date.
    • curtime: Returns the current system time.
    select now(); # 2023-06-06 09:36:54
    select curdate(); # 2023-06-06
    select curtime(); # 09:36:56
    
  • Fetch partial information of time and date

    • Dates: year(), month(), day(), monthname()
    • Time: hour(), minute(), second()
    • Several special ones:
      • quarter(): Returns the quarter corresponding to the date.
      • weekofyear: Returns the week of the year.
      • dayofyear: Returns the day of the year.
      • dayofmonth: returns the day of the month
      • dayofweak: returns the day of the week (Sunday is 1)
  • Conversion between time and seconds

    • The number of seconds is only related to the time, not the date.

    • Conversion formula: h×3600 + m×60 + s.

    • time_to_sec Convert time to seconds and sec_to_timeconvert seconds to time.

      select curtime(), time_to_sec(now()), sec_to_time(time_to_sec(now()));
      # 09:46:04  35164  09:46:04    
      
  • format

    • Display date and time in a custom format

    • placeholder in fromt format string

      %Y 年,四位数字
      %y 年,后两位数字
      %m 月 ,数字[1-12]
      %M 月名 
      %d 日,月份里的第几天,两位数字[1-31]
      %D 带有英文前缀的月中的天 
      %H 小时,24进制 [0-23]
      %h 小时,12进制[0-11]
      %i 分钟 [0-59]
      %s | %S 秒 0-59
      
    • date_format(date, format): formatted date

      select date_format(now(), '%m/%d-%y')
      from dual; # 06/06-23
      
    • time_format(date, format): formatted time

      select
        time_format(curtime(), '%h 点 %i 分 %s 秒')
      from dual; # 09 点 55 分 05 秒
      
  • String to date:str_to_date

    select
      str_to_date('2000-1-2', '%Y-%m-%d'),
      str_to_date('May 1, 2023', '%M %d,%Y')
    from dual;
    # 2000-01-02  2023-05-01 
    
4. Information function
  • versionQuery MySQL version number
  • userQuery the currently logged in account
  • databaseQuery the currently used database
5. Process control function
  • iffunction

    • grammar:if(expr, trueValue, falseValue)

    • select if(10 < 5, 'true', 'false') as "10 < 5"; #false
      
  • casefunction

    • grammar

      case [field_x]
        when XX then [statement-1]
        when XX then [statement-2]
        ...
        else [statement-n]
      end
      
    • Required when XX is a specific value case [field_x], required when XX is a conditional expressioncase

      /*
       * 查询员工的工资、部分编号和 new_salary,其中 new_salary 的计算如下
       *   部门编号如果是 30,new_salary 为 1.2 倍工资
       *   部门编号如果是 40,new_salary 为 1.25 倍工资
       *   部门编号如果是 50,new_salary 为 1.3 倍工资
       *   其他部门,new_salary 为原工资
      */
      
      select salary, department_id,
        case department_id
          when 30 then salary*1.2
          when 40 then salary*1.25
          when 50 then salary*1.3
          else salary
        end as new_salary
      from employees;
      
      /*
       * 查询员工的名字、工资以及工资级别 grade,grade 计算如下
       *   如果工资大于 20000,grade 为 A 级
       *   如果工资大于 15000,grade 为 B 级
       *   如果工资大于 10000,grade 为 C 级
       *   否则,grade 为 D 级
      */
      
      select first_name, salary,
        case
        when salary > 20000 then 'A'
        when salary > 15000 then 'B'
        when salary > 10000 then 'C'
        else 'D'
        end as grade
      from employees;
      

Common multi-line functions

1.Overview
  • Multi-row functions are also known as aggregate functions.
  • Used for statistics.
  • Classification: sumsummation, avgaverage value, maxmaximum value, minminimum value, countnumber of calculations.
2. Features
  • sum and avg are generally used to process numeric values.
  • max, min, count can handle any type.
  • The above grouping functions all ignore null values.
  • It can be used with distinct to implement deduplication operations.
  • The fields queried together with the grouping function are required to be the fields after group by.
3. Examples
  • easy to use

    select
      sum(salary),
      avg(salary),
      min(salary),
      max(salary),
      count(salary)
    from employees;
    
  • with distinctcollocation deduplication

    select
      sum(distinct salary),
      avg(distinct salary),
      min(distinct salary),
      max(distinct salary),
      count(distinct salary)
    from employees;
    
  • About countfunctions

    • count(expression): Returns NULLthe number of rows that do not contain a value.
    • count(*): The number of rows in the returned result set, NULLthe number of rows that contain values, that is, all rows.
    • count(distinct expression): Returns NULLthe number of unique rows that do not contain a value.

Listen quietly, there is a voice saying I love you. ——Mr. Turtle, "Boys Don't Cry"

Guess you like

Origin blog.csdn.net/m0_60610120/article/details/131062693
Recommended