MySQL common OJ routines

insert image description here

MySQL query manual:

1. Common keywords:

Prioritization:

from + on + join + where + group by + 聚合函数 + having + select + distinct + order by + limit offset + parition by

on & where: situations where it may be used at the same time

  • The fatal point of left and right connections:

    When connecting left and right, if a row in the left table does not correspond to a row in the right table, keep a left row + empty information

    It is impossible to filter out a row with an empty column by on cul is not null

  • Advantages of inner joins:

    Automatically filter rows containing null

  • When using join on + where at the same time:Prepare to use null information

    1. Contains null values ​​after join on
    2. Use where to filter null values

having: a good helper for group by

  • After group by, all operations are based on the first row of each group by default. If you want to enter the internal statistics of each group, you can only use having

    select * from employees group by emp_no having count(salary) > 15;
    

in & not in: containing & not

  • in & =:

    //当明确后者的数据集中只有一个数据时,只能使用 = 
    //反之,数据集中有多个元素时使用in
    

The location added by distinct:

  • Basic position: after select

    //select的执行优先级高于order by高于limit offset
    //所以只要 select 先筛一层,order by再排序,limit offset再筛一层,即可
    
  • Cohesive function location: inside count()

    select distinct salary
    from employee e1
    where (select count(distinct salary) from employee e2 where e1.salary < e2.salary) = N-1;
    

The relationship between group by and partition by:

  • Semantically:
    1. Emphasize the data as a whole after group by: each movement is based on the first of a group
    2. Emphasis on individual data after partition by: one column is used for grouping + sorting within the group according to other columns in the group
  • Syntactically:
    1. group by can be used independently
    2. partition by can only be used with built-in functions and used inside over()
  • After group by, the non-having operation only displays the first line instance for each group:
    group by

view:

  • Semantically: Find out a subtable, create a view to save it, which is equivalent to a reference

    Grammatically: the sql statement of the internal query subtable does not need to be added;

    create view view_name as(
    	select * from table1 group by id order by score
    );
    

or and union:

  • Using or will cause the index to fail, and the search efficiency is low when the amount of data is large
  • It is generally recommended to use union instead of or

coalesce():

  • Parameters: multiple parameters
  • Function: output the first non-empty parameter from left to right
  • Application Scenario: Termination Special Judgment

Temporary assignment of a row in the table: case

  • grammar:

    select (
    case
        when mod(id, 2) == 1 and id != sum then id+1
        when mod(id, 2) == 1 and id == sum then id
        else id-1
    end
    ) student, id
    from seat, (select count(*) sum from seat) sum_table
    

Second, the classic model:

Deduplicate/Different:

  • Method 1: desc

    select desc salary from salaries order by salary desc;
    
  • Houji: group by

    select salary from salaries group by salary order by salary desc;
    
  • Inside and outside of group by:

    1. Inside: having dominant inspection of multiple elements within a group
    2. External: select where join on dominates the review of a group as a whole as an element

Satisfy the maximum value: more than one row may be obtained

  • Satisfying the uniqueness of the most valuable: sorting

    select * from employees order by hire_date limit 1;
    
  • Satisfying the most value is not unique: in sub-table or = sub-table

    select * from employees where hire_date in (select MAX(hire_date) from employees); 
    
    select * from employees where hire_date = (select MAX(hire_date) from employees); 
    

Rank nth:

  • rank() over(): the sorting result is used as a sub-table and directly participates in the query

    # rank()效果为 1 1 3
    select * from (select *,rank() over(order by score desc) as 'Rank' from table1) where Rank = n;
    
  • dense_rank() over(): The sorting result is used as a sub-table, directly participating in the query, correct

    # dense_rank()效果为 1 1 2
    select * from (select *,dense_rank() over(order by score desc) as 'Dense_Rank' from table1) where Dense_Rank = n;
    
  • row_number(): The sorting result is used as a sub-table, directly participating in the query

    # row_number()效果为 1 2 3
    select * from (select *, row_number() over(order by score desc) as 'Row' from table1) where row_number = n;
    
  • select distinct + order by: plus sub-table query

    select distinct score from table1 order by score limit 1 offset n-1;
    
  • group by + order by: Only one group is left after group by, and it is executed in priority over order by

    select score from table1 group by score order by score limit 1 offset n-1;
    
  • count + distinct: plus sub-table query

    select distinct salary from employee e1
    where (select count(distinct salary) from employee e2 where e1.salary <= e2.salary)=N+1
    
  • count + group by: plus join table query

    select distinct e1.salary
    from employee e1, employee e2
    where e1.salary <= e2.salary
    group by e1.salary
    having count(distinct e2.salary) = N+1
    

Grouping, query information within the group:

  • Having statistical information within the group:

    select *, count(course) from student group by id having count(course) >= 2;
    
  • Whether group by and count conflict:

    select title, count(title) s from titles group by title having s>1;
    				分组依据列可以是count参数
    # 虽然group by之后非having操作每组都是对组首操作,但是count()等函数是对整组操作
    				组内列也可以是count参数
    select title, count(emp_no) s from titles group by title having s>1;
    
  • Grouping as a sub-table: the content obtained by sub-table query will not be repeated because it is the head of the group

    select Email from Person
    where id in (select id from Person group by email having count(Email) > 1));
    

Null information in multi-table join:

  • Use the left and right join + is null to solve the problem of finding rows that are not XXX:

    select * from employee e left join depart d 
    on e.dep_no = d.dep_no and e.emp_no = d.emp_no
    where d.emp_no is null;
    
  • The effect is equivalent to not in

    select * from employee
    where emp_no is not in (select distinct emp_no from depart);
    
  • Left and right joins + is not null, slightly changing the semantics can also solve the problem:

    select * from employee e left join depart d 
    on e.dep_no = d.dep_no and e.emp_no != d.emp_no
    where d.emp_no is not null;
    
  • Use with coalesce():

    select s1.id id, coalesce(s2.student, s1.student);
    from seat s1 left join seat s2
    on ((s1.id + 1)^1)-1 = s2.id
    order by s1.id;
    

The number of occurrences of a character in a string

  • String concatenation:

    concat("MySQL中字符串连接");
    
  • String replacement:

    replace(string, 'a', 'b');
    
  • String length:

    length();
    
  • In the string, the number of occurrences:

    select length(string)-length(replace(string, ',', ''))
    from strings;
    

Tied & non-tied rankings:

  • 1 1 2:dense_rank()

    select dense_rank() over(order by socre) 'dense_rank'
    from table1;
    
  • 1 1 3:rank()

    select rank() over(order by desc) 'rank'
    from table1;
    
  • 1 2 3:row_number()

    select rank() over(order by desc) 'row_number'
    from table1;
    

The difference between subtable query and join table query:

  • Subtable query: take the information of one row in this table and compare it row by row in another table

    select * 
    from scores s1
    where (select count(distinct salary) from scores s2 where s1.score <= s2.score) = N;
    
  • Joint table query: first Cartesian product, then on filter, and then extract information, null information is also particularly useful

    select * 
    from scores s1, scores s2
    where e1.salary <= e2.salary
    group by s1.id 
    having count(distinct e2.salary) = N;
    

Guess you like

Origin blog.csdn.net/buptsd/article/details/127475792