我们先给两张表:
tb_dept
tb_emp
/* 自然连接, 依靠相同的属性列连接,没有相同则不连接 */
select *
from tb_emp as t1
natural join tb_dept as t3;
/* 左连接, 部门 - 员工,没有相同则为null */
select *
from tb_dept as t1
left join tb_emp as t2 on t1.dno = t2.dno
ORDER BY t1.dno ASC;
/* 右连接, 同左连接一样 */
select *
from tb_dept as t1
right join tb_emp as t2 on t1.dno = t2.dno
ORDER BY t1.dno ASC;
/* 内连接, 显示左边、右边共有的 */
select *
from tb_emp as t1
inner join tb_dept as t2
ORDER BY t1.eno ASC;
如果我们要从数据库中取出各部门的信息,统计到Excel表里,就可以用到以上的连接:
import openpyxl
import pymysql
from pymysql.cursors import Cursor
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = '部门信息'
sheet.append(('编号', '名字', '地点', '员工编号', '员工姓名'))
conn = pymysql.connect(host='xxxx',
port=xxxx,
user='xxxx',
password='xxxx',
database='xxxx',
charset='utf8mb4')
try:
with conn.cursor() as cursor: # type: Cursor
cursor.execute(' \
select t1.dno, t1.dname, t1.dloc, t2.eno, t2.ename\
from tb_dept as t1\
left join tb_emp as t2 on t1.dno = t2.dno\
ORDER BY t1.dno ASC')
while row := cursor.fetchone():
sheet.append(row)
except pymysql.MySQLError as err:
print(err)
finally:
conn.close()
file.close()
wb.save('部门表.xlsx')
结果如下:
同理也可获取获取员工的统计信息保存在csv中: