Python--day43()

昨日内容:

一. 外键的变种 (*************)

唯一索引

unique('name') : 此列是不能重复的
联合唯一索引:
unique('name', 'age') : 这两列的值不能重复

一对多
department:
id depart_name
1 公关部
2 xxx 部

user:
id username depart_id (外键的约束)
1 root 1
2 root2 2
3 root3 1

一对一

看业务的需求
user:
id username depart_id (外键的约束)
1 root 1
2 root2 2
3 root3 1

blog:
id url user_id (唯一 + 外键约束)
1 /root/ 1
2 /root3/ 3

多对多

user:

id username
1 root
2 root2
3 root3


host:
id hostname
1 c1.com
2 c2.com
3 c3.com


user2host:

id uid hid (联合唯一 + 外键)
1 1 1
2 1 2
3 3 1
4 3 3




二. 数据行的详细操作


增:
insert into t1 (name, age) values ('lxxx', 12);
insert into t1 (name, age) values ('lxxx', 12), ('xxxxx', 13), ('xxxxxx', 13);
insert into t1 (name, age) select name, age from t2;

删:
delete from t1;
delete from t1 where name='xxx' and age!=12;

更新:
update t1 set name='xxx', age=123 where name='xxxx' and age=13;

查询:

通配符:
like name '李'
% : 匹配所有
_ : 匹配一个字符

限制取数据:
limit 从第几(索引)条开始取, 去多少条数据

分页: (***********)
page = 1,2,3,4,5...n
offset = 10

limit (page-1)*offset, offset;

排序:
order by 列名 asc(升序), desc(降序)


分组:
将数据按照某一列进行分组

group by + 聚合函数 (count/sum()/avg()/max()/min())

having

连表:
left join :
左边的全部显示

right join:
右边的全部显示

left join


今日内容:


一. 作业

navcate formysql

1、查询所有大于60分的学生的姓名和学号

思路:
那几张表:
关联 2张表: student score

select * from score left join student on score.student_id = student.sid;



查询没学过“李平”老师课的同学的学号、姓名



查询学过“李平”老师课的同学的学号、姓名



"李萍老师"教的课程ID


查询
至少有一门课与 学号为“1”的同学所学课程相同 的同学的学号和姓名


1 2,4


select course_id from score where student_id=1; ## 1,2,4


select student_id from score where course_id in (select course_id from score where student_id=1)

select sid ,sname from student where sid in (select student_id from score where course_id in (select course_id from score where student_id=1) having sid!=1)


select student.sid, student.sname from student left join score on student.sid = score.student_id where sid!=1 and course_id in (select course_id from score where student_id=1)




tee : 重定向导入某一个文件






二. pymysql (Python操作MySQL)



pip3 install pymysql



注意:

a. conn, cursor 用完了需要关闭资源连接

b. 查询的时候, fetchone, fetchmany, fetchall, 默认返回的是元组, 需要返回字典的话: cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

c. 删除和更新的时候, 需要在execute之后, 添加 conn.commit()









猜你喜欢

转载自www.cnblogs.com/wangyong123/p/11031151.html