SELECT*FROM beauty; SELECT*FROM boys; # 笛卡尔乘积现象 SELECT NAME, boyName FROM boys,beauty; # 使用连接查询解决 SELECT NAME,boyName FROM boys,beauty WHERE beauty.boyfriend_id = boys.id;
等值连接
查询员工名和对应的部门名
1 2 3
SELECT last_name,department_name FROM employees,departments WHERE employees.department_id = departments.department_id;
附带筛选条件
1 2 3
SELECT department_name,city FROM departments,locations WHERE departments.location_id = locations.location_id AND city LIKE'_o%';
理顺思路
理顺sql语句逻辑: 1、FROM employees,jobs WHERE jobs.job_id = employees.job_id 通过两个大表的相同部分进行合成一个大表 2、GROUP BY job_title 通过job_title进行分组,将相同的job_title分成一个个小表,count()会将一个个小表的数据全部统计进行分组统计 3、SELECT job_title,COUNT() 通过SELECT 显示并统计个个小表的job_title最后合成大表显示出来 4、ORDER BY COUNT(*) desc; 排序
非等值连接
1 2 3 4 5 6
SELECT*FROM job_grades; # 查询圆工的工资和工资级别 SELECT salary,grade_level FROM employees,job_grades WHERE job_grades.lowest_sal <= employees.salary AND employees.salary <= job_grades.highest_sal; #WHERE salary between job_grades.lowest_sal AND job_grades.highest_sal;
自连接
1 2 3 4 5 6
#查询员工名和对应上级名 SELECT e.employee_id,e.last_name,m.manager_id,m.last_name FROM employees AS e,employees m WHERE m.employee_id = e.manager_id;
语法: SELECT 查询列表 FROM 表1 别名 inner join 表2 别名 on 连接条件
1 2 3 4
SELECT last_name,First_name FROM employees e inner JOIN departments d ON e.department_id = d.department_id;
非等值连接
1 2 3 4 5 6
SELECT grade_level,count(*) FROM employees e innerjoin job_grades g on e.salary between g.lowest_sal and g.highest_sal GROUPBY grade_level ORDERBY grade_level asc;