目标就是建立这么个下图的东西
然后使用进行一些汇总查询操作
用的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
还有各种其他操作,都是大差不差,就是平常记录,很水的分享