python学习笔记 day44 mysql 练习题(二)

1. 练习题二题目来自于:http://www.cnblogs.com/wangfengming/articles/7889786.html

这部分的习题 大致看了一下,没有实际创建表来做,这里选几个比较有代表性的题大致说一下思路:

表的信息如下:

24. 删除工资重复的人员,保留年龄最大的一个:

思路:

先对人员person表基于salary分组,然后统计属于一组(salary相同的)id个数--count(id)是否大于1 ,以及选max(age) 就能基于分组整合出来一张表 ,将这张表与原始表基于salary建立关联,进行连接,连接好之后的一张新表 筛选count(id)>1  age<max(age)---因为是工资相同的,保留年龄最大的那个人  ,这样选出来的都是应该被删掉的,接下来那一张新的表(由person表复制的)删掉应该删掉的信息即可;

create table person_copy select * from person;  -- 首先复制一张新的表,跟person数据一样,便于删掉信息

delete from person_copy where id in (

select id from perosn as t1 left join 
( select salary,count(id)as number,max(age)as age from person group by salary ) as t2
on t1.salary=t2.salary 
where number>1 and t1.age<t2.age;   -- 内层的select主要是基于salary分组,为了跟原来的表进行连接,根据count(id)>1 age<max(age)筛选出需要删掉的数据项
)

27. 查看哪些人员的门派已登记地理位置.

思路: 使用联合查询,或者内连接查询:

select class,address from person,dept where person.class=dept.dname;  -- 联合查询

select class,address from person inner join dept on person.class =dept.name;-- 内连接查询

28. 查询所有人员门派的位置信息,不存在位置信息则不显示

思路:使用左连接查询

select name,class,address from person left join dept on person.class=dept.dname;

29.在湖北省内的门派中的人员有哪些.

思路:使用联合查询:

select name,class,address from person,dept where person.class=dept.dname and address="湖北";

30.在陕西省内门派中的工资小于5000,年龄大于20岁的人员有哪些,按主键倒序排列

思路: 使用联合查询:

select name,age,salary,class,address from person,dept where person.class=dept.dname and salary<50000 and age>20 and address="陕西" order by person.id desc;

猜你喜欢

转载自www.cnblogs.com/xuanxuanlove/p/9900985.html