数据仓库练习--星形模型查询,python 插入 以及表连接 和group操作

目标就是建立这么个下图的东西
在这里插入图片描述
然后使用进行一些汇总查询操作

用的python代码和数据库工具 和数据库表单在下面的github里面
https://github.com/WunaiDczh/data_warhouse_practice
上传个github真的太难了,全看脸了

准备数据库

这里直接省略了branch 这个维度,按照其他三个维度和事实表建立,如下图
在这里插入图片描述
item表
在这里插入图片描述
location表单
在这里插入图片描述
time 表单,这里偷懒了,其实day_of_week也应该和quarter属性一样用enum类型,偷懒了
在这里插入图片描述
在这里插入图片描述

sales 事实表
在这里插入图片描述
事实表添加外键
在这里插入图片描述

Python向数据库添加一些数据

关于Python和Mysql连接 请参考这一篇文章 python如何连mysql数据库
以及 Python连接MySQL数据库方法介绍(超详细!手把手项目案例操作)

新建一个python 项目,
在这里插入图片描述

直接 pip install mysql,安装 mysql.connector
在这里插入图片描述
数据库连接过程

import pymysql
import random
conn=pymysql.connect(host = '127.0.0.1' # 连接名称,默认127.0.0.1 
,user = 'root' # 用户名
,passwd='root' # 密码
,port= 3306 # 端口,默认为3306
,db='data_warehouse' # 数据库名称
,charset='utf8' # 字符编码
)
cur = conn.cursor()	# 生成游标对象
sql=“这里就是sql语句了”
print(sql)#我是习惯打印一次,SQL语句
cur.execute(sql)  # 执行SQL语句
conn.commit() # 提交到数据库执行
data = cur.fetchall()  # 通过fetchall方法获得数据
print(data)
cur.close() # 关闭游标
conn.close()	# 关闭连接
## https://www.bilibili.com/read/cv3418619/

应为要随机生成一些文本插入到数据库中,关于python的随机生成参考了下面的小姐姐的随笔
python生成随机数、随机字符串

贴一个随机的sale表插入代码吧

import pymysql
import random
conn=pymysql.connect(host = '127.0.0.1' # 连接名称,默认127.0.0.1 
,user = 'root' # 用户名
,passwd='root' # 密码
,port= 3306 # 端口,默认为3306
,db='data_warehouse' # 数据库名称
,charset='utf8' # 字符编码
)
cur = conn.cursor()	# 生成游标对象


#sql = "select * from `item` "  # SQL语句

##sql="insert into item (item_name,brand,type,supplier_type) values('手机','小米',2,'富士康')"
for i in range(500):

    time_key = str(random.randint(1,100))
    item_key = str(random.randint(1,100))
    location_key = str(random.randint(1,100))
    units_sold =str(random.randint(1,50))
    dollars_sold=str(random.randint(1,50))
    profit=str(random.randint(1,50))
    sql="insert into sales (time_key,item_key, location_key,units_sold,dollars_sold,profit)"+\
        "values('"+time_key+"','"+item_key+"','"+location_key+"','"+units_sold+"','"+dollars_sold+"','"+profit+"');"
    print(sql)
    cur.execute(sql)  # 执行SQL语句
    conn.commit() # 提交到数据库执行

    data = cur.fetchall()  # 通过fetchall方法获得数据
    print(data)


cur.close() # 关闭游标
conn.close()	# 关闭连接
## https://www.bilibili.com/read/cv3418619/

中间测试插入的时候,表单主键的自增ID,会记住被删除记录的主键ID,解决办法:
alter table 表名 AUTO_INCREMENT=1;

表连接 和 group by操作


select city, sum(profit)
from sales,time,item,location
where time.time_key=sales.time_key and item.item_key=sales.item_key and location.location_key=sales.location_key 
group by city 

在这里插入图片描述
还有各种其他操作,都是大差不差,就是平常记录,很水的分享

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值