1、在school数据库中创建两个数据表
输入user school
输入create table classes(id int primary key auto_increment,label char(30),description text) charset="utf8";
即在school数据库中创建了classes表
输入create table t_classes(id int primary key auto_increment,t_id int,c_id int,delete_flage char(4)) charset="utf8";
即在school数据库中创建了t_classes表
2、用python的pymysql模块给mysql添加数据
(1)首先给classes数据表添加数据
# coding:utf-8
import random
import pymysql
db = pymysql.connect(
user="root",
password="1234",
host="localhost",
database="school",
charset="utf8"
)
cursor = db.cursor()
pro = ["python", "c", "java", "php", "linux"]
for index, i in enumerate(pro):
description = "%s 是世界上第%s好的语言" % (i, index + 1)
sql = "insert into classes(label,description) value('%s','%s')" % (i, description)
# sql = "update classes set description='%s' where id = %s" % (description, index + 1)
try:
cursor.execute(sql)
except Exception as e:
print(e)
else:
print(sql)
db.commit()
cursor.close()
db.close()
即在数据表中添加了这些数据
(2)给t_classes数据表添加数据
# coding:utf-8
import random
import pymysql
from functools import partial
def exect(cursor, sql):
try:
cursor.execute(sql)
except Exception as e:
print(e)
else:
print(sql)
def outer(fun):
def inner(database="school"):
db = pymysql.connect(
user="root",
password="1234",
host="localhost",
database=database,
charset="utf8"
)
cursor = db.cursor()
sqls = fun()
func = partial(exect, cursor)
if isinstance(sqls, list):
for sql in sqls:
func(sql)
elif isinstance(sqls, str):
func(sql)
db.commit()
cursor.close()
db.close()
return inner
@outer
def insert_tClass():
sqls = []
for i in range(200):
t_id = random.randint(1, 100)
c_id = random.randint(1, 5)
sql = "insert into t_classes(t_id,c_id,delete_flag) value(%s,%s,'T')" % (t_id, c_id)
sqls.append(sql)
return sqls
if __name__ == '__main__':
insert_tClass()
即在数据库中添加了这些数据
3、查询
做好了上面的准备工作之后,我们可以开始查询了
(1)比如,我要查询所有python科目的老师
输入select * from teacher where project="python"
上面的个代码并没有用到多表联查,因为teacher这个表中,就有project这一项,直接就可以查,如果没有的话,我们就借助其它的方式。
输入select * from teacher where project=(select label from classes where id=1);
得到的结果是一样的,因为classes 数据表中id为1对应的字段label就是python
(2)查询teacher表中,id为1的老师的project在classes表中对应的label和description
输入select label,description from classes where label=(select project from eacher where id=1);
(3)由于操作的失误,在teacher表中出现了一个课程,是classes的字段里没有的课程,现在需要把它找出来
输入select name,project from teacher where teacher.project not in(select label from classes);
得到了结果:
然后我们把这个出错的数据删掉:
输入delete from teacher where name='lee';
(4)删除teacher表的project字段,查询ID为1的老师对应的课程
输入select c.label,c.description from classes as c,t_classes as tc where tc.t_id=1 and tc.c_id=c.id;
如果想显示名字的话可以增加显示字段
输入select t.name,c.label,description from classes as c,t_classes as tc,teacher as t where tc.t_id=1 and tc.c_id=c.id and tc.t_id=t.id;
(5)查询课程ID为1对应的老师
输入select t.name,c.label from classes as c,t_classes as tc,teacher as t where tc.c_id=1 and c.id=1 and tc.t_id=t.id;