Home  >  Article  >  Database  >  MySQL basic multi-table query case sharing

MySQL basic multi-table query case sharing

WBOY
WBOYforward
2022-11-01 15:13:531386browse

This article brings you relevant knowledge about mysql, which mainly introduces the relevant content about multi-table query and some case sharing, including querying the name, age, position of employees, etc. Let’s take a look at the content below, I hope it will be helpful to everyone.

Recommended learning: mysql video tutorial

Multiple table query case

Data environment preparation

create table salgrade(
grade int,
losal int,
hisal int
) comment '薪资等级表';
insert into salgrade values (1,0,3000);
insert into salgrade values (2,3001,5000);
insert into salgrade values (3,5001,8000);
insert into salgrade values (4,8001,10000);
insert into salgrade values (5,10001,15000);
insert into salgrade values (6,15001,20000);
insert into salgrade values (7,20001,25000);
insert into salgrade values (8,25001,30000);

In this case, we mainly use the multi-table query syntax explained above to complete the following 12 requirements. There are only three tables involved here: emp employee table , dept department table, salgrade salary grade table.

Query employee’s name, age, position, department information (implicit inner join)

Table: emp, dept

Join condition: emp .dept_id = dept.id

select e.name , e.age , e.job , d.name from emp e , dept d where e.dept_id = d.id;

Query the name, age, position, and department information of employees younger than 30 years old (explicit inner connection)

Table: emp, dept

Connection conditions: emp.dept_id = dept.id

select e.name , e.age , e.job , d.name from emp e inner join dept d on e.dept_id =d.id where e.age < 30;

Query the employees Department ID, department name

Table: emp, dept

Connection conditions: emp.dept_id = dept.id

select distinct d.id , d.name from emp e , dept d where e.dept_id = d.id;

Query all employees older than 40 years old and the name of the department they belong to; if the employee is not assigned a department, it also needs to be displayed (outer connection)

Table: emp, dept

Connection conditions: emp.dept_id = dept.id

select e.*, d.name from emp e left join dept d on e.dept_id = d.id where e.age >40 ;

##Query the salary grade of all employees

Table: emp, salgrade

Connection conditions: emp.salary >= salgrade.losal and emp.salary <= salgrade.hisal

-- 方式一
select e.* , s.grade , s.losal, s.hisal from emp e , salgrade s where e.salary >=
s.losal and e.salary <= s.hisal;
-- 方式二
select e.* , s.grade , s.losal, s.hisal from emp e , salgrade s where e.salary
between s.losal and s.hisal;

Recommended learning:

mysql video tutorial

The above is the detailed content of MySQL basic multi-table query case sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete