Mysql-DQL (join query 1)

Class 6 join query

Meaning: Field of multi-table queries from the plurality of tables when a query
cartesian product phenomenon: m rows in Table 1, Table 2, there are n rows, m * n rows Results

The reason occurred: There is no valid connection conditions
How to avoid: Add a valid connection

classification:

   按年代:
   sq192
   sq199 推荐:支持内连接+外连接(左外和右外)+交叉连接
   按功能分类:
       内连接:
             等值连接
             非等值连接
             自连接
       外连接:
             左外连接
             右外连接
             全外连接
       交叉连接:

A, sql92 standard

1. Equijoins

The results of multi-table equivalent to the intersection portion of the multi connection table
n connection table needs to n-1 connections conditions
descending order table does not require
generally aliases tables
can be used with all previous clauses

#1、案例:查询员工名和对应的部门名
 SELECT
  last_name,
  department_name
FROM
  employees,
  departments
WHERE employees.department_id = departments.department_id;
#2、为表起别名
#案例 员工号、工种号、工种名
 SELECT
  last_name,
  e.job_id,
  job_title
FROM
  employees AS e,#因为是先执行from所以如果select哪里再用原始表表名就无法识别
  jobs AS j
WHERE e.`job_id`=j.`job_id`;
#3、二个表的顺序可以调换
#案例 员工号、工种号、工种名
 SELECT
  last_name,
  e.job_id,
  job_title
FROM
  employees AS e,
  jobs AS j
WHERE j.`job_id`=e.`job_id`;
#4.可以加筛选
#查询有奖金的员工名,部门名
 SELECT
  last_name,
  department_name
FROM
  employees AS e,
  departments AS d
WHERE e.`commission_pct` IS NOT NULL
  AND e.`department_id` = d.`department_id` 
#5、可以加分组
 #查询每个城市的部门个数
 SELECT
  COUNT(*),
  city
FROM
  locations AS l,
  departments AS d
WHERE l.`location_id` = d.`location_id`
GROUP BY l.`city` 
#6、加排序
#查询每个工种的工种名和员工的个数,并且按员工个数降序
SELECT COUNT(*),job_title 
FROM employees AS e,jobs AS j 
WHERE e.`job_id`=j.`job_id` 
GROUP BY job_title 
ORDER BY COUNT(*) DESC;
#7、三表连接
#查询员工名,部门名和所在城市
 SELECT
  last_name,
  department_name,
  city
FROM
  employees AS e,
  departments AS d,
  locations AS l
WHERE e.`department_id` = d.`department_id`
  AND l.`location_id`=d.`location_id`;

## 2, non-equivalent connection

#案例 查询每个员工的工资和工资等级
SELECT salary,grade_level
 FROM employees AS e,job_grades AS g 
 WHERE salary 
 BETWEEN g.`lowest_sal` AND g.`highest_sal`;

3, since the connection

#案例查询员工名和上级的名称
 SELECT
  e.last_name,
  e.employee_id,
  m.`last_name`,
  m.`employee_id`
FROM
  employees AS e,
  employees AS m
WHERE e.`manager_id` = m.`employee_id`;
Published 45 original articles · won praise 43 · views 7084

Guess you like

Origin blog.csdn.net/qq_42193790/article/details/104355053
Recommended