构建数据表

1、把dome.sql脚本复制到ubuntu系统的主目录下。
2、进入MySQL数据库,并选择testDB数据库。
3、使用source doem.sql 执行脚本,第一次执行会出现删除表失败的提示,属于正常现象,因为你数据库中没有这些表。

s_customer

客户表

s_dept

部门表

s_emp

员工表

s_image

图片表

s_inventory

库存表

s_item

项目表

s_longtext

文件表

s_ord

业务表

s_product

产品表

s_region

区域表

s_title

职位表

s_warehouse

仓库表

多表查询:

当需要查询的数据在多张表中,需要多张表同时查询。

select 字段 from 表1,表2 where 条件;

注意:条件是多表查询的基础,它是多张表联合在一起的依据,多表查询时如果不写条件会产生笛卡尔积。

查询出每位员工的姓名、工资、部门id、部门名。

select first_name,salary,dept_id,name from s_dept,s_emp where dept_id=s_dept.id;

注意:如果在多张表中有相同的字段,可以使用表名.字段名加以区别。

练习1:查询出每个部门所负责的区域。

select s_dept.name,s_region.name from s_dept,s_region while region_id=s_region.id;

取别名:

给字段取别名,可以提高查询结果的可读性;

给表取别名,可以精简查询语句;

select 字段名 as 别名 from 表名;
select 别名.字段 from 表名 as 别名;
select d.name,r.name from s_dept as d,s_region as r while region_id=r.id;

分组查询:

按照一定的标准给数据进行分组,然后合理的使用组函数,查询出需要的数据。

select 字段 from 表名 group by 字段;

查询出每个部门的员工数量?

select count(last_name),dept_id from s_emp,s_dept where dept_id=s_dept.id group by dept_id;

查询出部门员工数量大于n的部门名和部门ID?

having对分组数据过滤,它相当于select的where。

select 字段 from 表名 group by 字段 having 条件;
select count(lastname),dept_id,s_dept.name from s_emp,s_dept where dept_id=s_dept.id group by dept_id having count(last_name)>3;

SQL语句的执行顺序

select 组函数(字段),字段
    from 表名
    	where 条件
    		group by 分组标准
    			having 过滤分组后的数据
    				order by 排序标准

练习

查询出每个部门的员工数量,最高工资、最低工资、平均工资,显示顺序按平均工资排序。

select count(s_emp.id),max(salary),min(salary),round(avg(salary),2),dept_id,s_dept.name from s_emp,s_dept where dept_id = s_dept.id group by dept_id order by avg(salary);

链接查询

多表链接,通过调用where条件进行查询方式叫链接查询,当有空值时链接查询为:

内链接 inner join on,出现的结果一一对应,等值链接。

左链接 left join on,出现的结果是内链接+左表未对应的数据

右链接 right join on,出现的结果是内链接+右表未对应的数据

全链接 full join on,MySQL数据不支持,再现的结果是内连接数据+左、右表未对应的数据。

select 字段 from 左表 [inner|left|right|full] join 右表 on 连接条件;

查询出每位员工的姓名、工资、部门id、部门名,外加未分配部门的员工。

select first_name,salary,dept_id,name from s_dept right join s_emp on dept_id=s_dept.id;