Day 43 数据库 终结
消除重复行
-
在select后面列前使用distinct可以消除重复的行
-
distinct的使用需要放在第一个字段的位置,针对第一个字段进行去重。
select distinct 列1,... from 表名; 例: select distinct gender from students;
例如,统计下在学生表的所有的学生班级
select distinct class from student;
having
group by 字段 having 条件;
过滤筛选,主要作用类似于where关键字,用于在SQL语句中进行条件判断,过滤结果的。
但是与where不同的地方在于having只能跟在group by 之后使用。
练习:查询301班级大于班上平均成绩的学生成绩信息(name,平均分,班级)。
# 先求301班的平均成绩 select avg(achievement) as achi from student as a left join achievement as b on a.id=b.sid where class=301; # 判断301中的每个人平均成绩大于上面的到的平均成绩 select name,avg(achievement) from student as a left join achievement as b on a.id=b.sid where class=301 group by name having avg(achievement) > (select avg(achievement) as achi from student as a left join achievement as b on a.id=b.sid where class=301);
select distinct 字段1,字段2.... from 表名 as 表别名 left join 从表1 on 表名.主键=从表1.外键 left join .... where .... group by ... having ... order by ... limit start,count
-
-
from 表名[包括连表]
-
where ....
-
group by ...
-
select distinct *
-
having ...
-
order by ...
-
limit start,count
-
-
实际使用中,只是语句中某些部分的组合,而不是全部
Python操作mysql
pymysql 一般使用这个
MySQLDB
安装pymysql模块
pip install pymysql
使用pymysql模块操作数据库
import pymysql # from pymysql import * # 创建和数据库服务器的连接 connection conn = pymysql.connect(host='localhost',port=3306,user='root',password='root123456', db='student',charset='utf8') # 创建游标对象 cursor = conn.cursor() # 中间可以使用游标完成对数据库的操作 sql = "select * from student;" # 执行sql语句的函数 返回值是该SQL语句影响的行数 count = cursor.execute(sql) print("操作影响的行数%d" % count) # print(cursor.fetchone()) # 返回值类型是元祖,表示一条记录 # 获取本次操作的所有数据 for line in cursor.fetchall(): print("数据是%s" % str(line)) # 关闭资源 先关游标 cursor.close() # 再关连接 conn.close()
执行语句
#执行sql,更新单条数据,并返回受影响行数 result = cursor.execute("SQL语句") #插入多条,并返回受影响的函数,例如批量添加 result2 = cursor.executemany("多条数据") #获取最新自增ID new_id = cursor.lastrowid
获取结果
#获取一行 result1 = cursor.fetchone() #获取多行[参数可以设置指定返回数量] result2 = cursor.fetchmany(整型) #获取所有 result3 = cursor.fetchall()
操作数据
#提交,保存新建或修改的数据,如果是查询则不需要 conn.commit() # 写在execute()之后