关于Python连接liunx中mysql数据库的方式在这一篇文章
Python连接Liunx中mysql数据库-保姆级教程
关于Python针对liunx中的mysql数据库进行增删改查操作的文章在这一篇可以看一下
Python连接Liunx中mysql数据库-增删改查
对于单表查询的学习可以看这一篇文章
Python对liunx中mysql数据库进行单表查询 10个案例带你了解
今天持续分享Liunx连接mysql数据库进行多表查询
首先创建两个表
1.dept表
CREATE TABLE `dept` (
`dept1` varchar(10) DEFAULT NULL,
`dept_name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
插入数据
2.emp表
CREATE TABLE `emp` (
`id` varchar(10) DEFAULT NULL,
`name` varchar(25) DEFAULT NULL,
`age` varchar(10) DEFAULT NULL,
`worktime` varchar(10) DEFAULT NULL,
`dept2` varchar(10) DEFAULT NULL,
`incoming` int(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
插入数据
python中连接liunx中mysql数据库
import pymysql
db = pymysql.connect(host='192.168.52.129',#数据库的ip地址
user='root',#连接名
passwd='',#你的密码
database='test',#数据库名称
port=3306)#端口号
curs = db.cursor()
1.列出每个部门里面有那些员工及部门名称
sql1 ='select name,dept_name from dept left join emp on dept.dept1 = emp.dept2;'
curs.execute(sql1)
print(curs.fetchall())
2.运维部门的收入总和
sql1 ='select sum(incoming) from dept left join emp on dept.dept1 = emp.dept2 where dept_name="yunwei";'
curs.execute(sql1)
print(curs.fetchall())
3.zhubo部入职员工的员工号
sql1 ='select id from dept left join emp on dept.dept1 = emp.dept2 where dept_name="HR";'
curs.execute(sql1)
print(curs.fetchall())
4.财务部门收入超过3000元的员工姓名
sql1 =‘select name from dept left join emp on dept.dept1 = emp.dept2 where dept_name=“chaiwu” and incoming>3000;’
curs.execute(sql1)
print(curs.fetchall())
5.找出zhubo部收入最低的员工的入职时间;
sql1 ='select min(incoming),worktime from dept left join emp on dept.dept1 = emp.dept2 where dept_name="zhubo" GROUP BY worktime;'
curs.execute(sql1)
print(curs.fetchall())
6.找出年龄小于平均年龄的员工的姓名,ID和部门名称
sql1 ='select name,id,dept_name from dept left join emp on dept.dept1 = emp.dept2 where age<(select avg(age) from emp);'
curs.execute(sql1)
print(curs.fetchall())
7.列出每个部门收入总和高于5000的部门名称
sql1 ='select dept_name from dept left join emp on dept.dept1 = emp.dept2 group by dept_name having sum(incoming)>5000;'
curs.execute(sql1)
print(curs.fetchall())
8.查出财务部门工资少于20000元的员工姓名
sql1 ='select name from dept left join emp on dept.dept1 = emp.dept2 where incoming<10000 and dept_name = "chaiwu";'
curs.execute(sql1)
print(curs.fetchall())
9.求收入最高的员工姓名及所属部门名称
sql1 ='select name,dept_name from dept left join emp on dept.dept1 = emp.dept2 where incoming=(select max(incoming) from emp join dept on emp.dept2 = dept.dept1) ;'
curs.execute(sql1)
print(curs.fetchall())
10.求员工收入小于5000元的员工部门编号名字及其部门名称;
sql1 ='select name,id,dept_name from dept left join emp on dept.dept1 = emp.dept2 where incoming<5000 '
curs.execute(sql1)
print(curs.fetchall())