mysql commonly used statement four: query operations in DQL

1 Average and decimal places

The table structure is as follows.
Insert picture description here
Query the scores of each post 平均数, and sort them in descending order of the scores , and keep the results 3位after the decimal point (after 3 digits 四舍五入)

select job, round(avg(score), 3) from grade
group by job
order by avg(score) desc;

Insert picture description here
Pay attention to the use of roundand avgfunctions.

2 Find options in table A that do not have table B

The table structure is as follows:
Insert picture description here
Insert picture description here
Find all employees who are not department leaders emp_no.

select emp_no from employees
where emp_no not in (select emp_no from dept_manager);

Insert picture description here
Here look up two tables at the same time, pay attention to not inthe use of keywords .

3 not inkeywords

The table structure is as follows:
Insert picture description here
Delete the duplicate record of emp_no, and only keep the record corresponding to the smallest id

delete from titles_test
where id not in(
    select * from (
        select min(id) from titles_test
        group by emp_no
    ) as t1
);

analysis

not inThe statement in the following brackets is to find the record with the smallest id among the duplicate records.

select * from (
    select min(id) from titles_test
    group by emp_no
) as t1

Insert picture description here
These three rows of records are to be deleted, just selectreplace the ones in the figure delete.

4 concatfunction to connect two fields

The table structure is as follows
Insert picture description here
. The last_name and first_name of all employees are spliced ​​together as the Name, separated by a space in the middle

select concat(last_name, ' ', first_name) as Name 
from employees;

Insert picture description here

5 表名 left join 表名 on 条件left outer join

The table structure is as follows to
Insert picture description here
Insert picture description here
find the task status of each person, and the output results are sorted in ascending order according to the person's id.

select p.id, p.name, t.content from person as p
left join task as t
on p.id = t.person_id
order by p.id;

Insert picture description here

Guess you like

Origin blog.csdn.net/Awt_FuDongLai/article/details/114519674