0

我有 2 张表 TBL1 和 TBL2。

TBL1有 2 列id, nSql.
TBL2有 3 列date, custId, userId.
我在 TBL1 中有 17 行,id 为 1 到 17。每个 nSql 中都有一个 SQL 查询。

例如 nSql 为

id == 1 是:"select date, pId as custId, tId as userId from TBL3"
id == 2 是:"select date, qId as custId, rId as userId from TBL4"...

nSql 结果总是相同的 3 列。

下面的查询运行并将数据放入表 TBL2。如果 TBL2 中已经有当天的数据,我希望查询用新数据替换数据。如果 TBL2 中没有数据,我想以正常方式放置数据。

例如,如果我在早上运行查询,如果我想在晚上再次运行它,我希望新数据替换当天的旧数据,因为每天都会将数据插入到 TBL2 中。

如果数据已经存在(如果由同事运行),我也不希望那天有重复的数据,这也是一种预防措施。

我该怎么做?

谢谢你。

(我是python的新手,如果有人可以分步解释并在代码中显示,我将不胜感激)

import MySQLdb

# Open connection
con = MySQLdb.Connection(host="localhost", user="root", passwd="root", db="test")

# create a cursor object 
cur = con.cursor()

selectStatement = ("select nSql from TBL1") 
cur.execute(selectStatement)
res = cur.fetchall()
for outerrow in res:
    nSql = outerrow[0]
    cur.execute(nSql)
    reslt = cur.fetchall()

    for row in reslt:
        date = row[0]
        custId = row[1]
        userId = row[2]
        insertStatement = ("insert into TBL2( date, custId, userId) values ('%s', %d, %d)" % (date, custId, userId))
        cur.execute(insertStatement)
        con.commit() 
4

1 回答 1

0

时间戳(使用datetime)插入到表中的所有数据。在插入之前,从日期时间当天是今天的表中删除。

对于 MySQL,您可以使用to_days()带有日期的函数来获取日期时间所在的日期:https ://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_to-days

插入新行时,now()会让你使用当前时间对应的日期时间值:https ://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_now

于 2013-03-28T12:39:39.317 回答