Python进行数据的Join关联操作及从分表取数据一例

这样的功能主要用在两表分别在不同的数据库上,在数据库层面不同步数据关联不了的情况。且目前,被关联的表公仅支持是key/value两列数据的情况。
1、数据准备
-- 主表
select * from x_student_scores
insert into x_student_scores
select 1,'语文',1,98 union all 
select 2,'数学',1,99 union all 
select 3,'外语',1,35 union all 
select 4,'物理',1,65 union all 
select 5,'化学',1,55 union all 
select 6,'生物',1,90 union all 
select 7,'政治',1,98 union all 
select 8,'地理',1,100 union all 
select 9,'历史',1,89 union all 
select 10,'语文',2,98 union all 
select 11,'数学',2,99 union all 
select 12,'外语',2,35 union all 
select 13,'物理',2,65 union all 
select 14,'化学',2,89 union all 
select 15,'生物',2,90 union all 
select 16,'政治',2,87 union all 
select 17,'地理',2,78 union all 
select 18,'历史',2,96 ;
-- 代码表
select * from x_student
insert into x_student
select 1,'汪良品' union all
select 2,'张宁全';

2、数据库中查询SQL
select a.id,a.kemu,a.student_id,b.`name` student_name,scores 
from x_student_scores a
left join x_student b
on a.student_id=b.id

数据结果
id  kemu  student_id  student_name  scores
1  语文  1  汪良品  98
2  数学  1  汪良品  99
3  外语  1  汪良品  35
4  物理  1  汪良品  65
5  化学  1  汪良品  55
6  生物  1  汪良品  90
7  政治  1  汪良品  98
8  地理  1  汪良品  100
9  历史  1  汪良品  89
10  语文  2  张宁全  98
11  数学  2  张宁全  99
12  外语  2  张宁全  35
13  物理  2  张宁全  65
14  化学  2  张宁全  89
15  生物  2  张宁全  90
16  政治  2  张宁全  87
17  地理  2  张宁全  78
18  历史  2  张宁全  96


3、Python实现的代码
/Users/nisj/PycharmProjects/EsDataProc/Data_Join.py
# -*- coding=utf-8 -*-
import MySQLdb
import warnings
import datetime
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

warnings.filterwarnings("ignore")

db_config = {
    'host': '127.0.0.1',
    'user': 'root',
    'passwd': '123',
    'port': 3306,
    'db': 'tv'
}


def getDB():
    try:
        conn = MySQLdb.connect(host=db_config['host'], user=db_config['user'], passwd=db_config['passwd'],
                               port=db_config['port'])
        conn.autocommit(True)
        curr = conn.cursor()
        curr.execute("SET NAMES utf8");
        curr.execute("USE %s" % db_config['db']);

        return conn, curr
    except MySQLdb.Error, e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])
        return None, None

conn, curr = getDB()

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)


sql_text = "select table_name from information_schema.tables where table_schema='tv' and table_name like 'x_student_scores%';"
curr.execute(sql_text)
tab_list = curr.fetchall()

col_datas_union = []
for tab_name in tab_list:
    tab_name = tab_name[0]

    sql_text = "select id,kemu,student_id,scores from tv.%s ;" % (tab_name)
    curr.execute(sql_text)
    col_datas = curr.fetchall()

    col_datas_union.extend(col_datas)

sql_text = "select id,name from tv.x_student;"
curr.execute(sql_text)
col_datas = curr.fetchall()

main_list = col_datas_union
dict_list = dict(col_datas)

result_list = [[main_item[0],main_item[1],main_item[2],main_item[3], dict_list.get(main_item[2], 0)] for main_item in main_list]

print "序号","科目","学号","分数","学生姓名"
for rl in result_list:
    print rl[0],rl[1],rl[2],rl[3],rl[4]

curr.close()
conn.close()

数据结果:
序号 科目 学号 分数 学生姓名
1 语文 1 98 汪良品
2 数学 1 99 汪良品
3 外语 1 35 汪良品
4 物理 1 65 汪良品
5 化学 1 55 汪良品
6 生物 1 90 汪良品
7 政治 1 98 汪良品
8 地理 1 100 汪良品
9 历史 1 89 汪良品
10 语文 2 98 张宁全
11 数学 2 99 张宁全
12 外语 2 35 张宁全
13 物理 2 65 张宁全
14 化学 2 89 张宁全
15 生物 2 90 张宁全
16 政治 2 87 张宁全
17 地理 2 78 张宁全
18 历史 2 96 张宁全

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值