在表1中有一列名为calendar_date的记录格式为10/8/2010,在表格2中有一列名为date的列,格式为10/8。 在表2中还有另外两列名为daynoleap,dayleap,表示无线电年或闰年的朱利安日期。现在我需要将这两个列中的一列添加到table1,由列calendar_date的年份确定。如果是2010,它除以4并且有一个余数,所以我将table2的daynoleap列添加到table1的julian_date列。否则,我添加dayleap列。PostgreSQL中子查询返回的多行
我收到一个错误:通过使用下面的代码作为表达式使用子查询返回的多行:(我相信现在的错误来自查询语句)。所有的代码都在一个forloop内,其中我得到了单年的变量(例如2010),monthDate(例如10/8)的记录。
while int(year)%4 == 0:
statement2="UPDATE table1 SET julian_date = (SELECT dayleap FROM table2 WHERE date = '%s') WHERE (SELECT date FROM table2) = '%s'"
statement2=statement2 % (monthDate, monthDate)
curs2 = conn.cursor()
curs2.execute(statement2,)
conn.commit()
显然有代码有问题,以防止它得到单个记录更新。但是因为我已经有了更新语句的WHERE子句,所以我也没有看到语句的问题。我试图将这两个值切换到等号的左侧和右侧等,但没有奏效。有人可以帮助我?
解决方案:
我使用下面的代码解决了这个问题:
statement1='SELECT date FROM table1'
curs1.execute(statement1)
records1=curs1.fetchall()
for record1 in records1:
date = record1[0].split('/')
monthDate=date[0]+ '/'+date[1]
if int(year)%4 == 0: #for leap year
statement_tmp = "SELECT dayleap FROM table2 WHERE date = '%s'" % (monthDate) #the date column in table2 is in format of month/date.
curs1.execute(statement_tmp)
julianDate1 = curs1.fetchall()
julianDate = curs1.fetchall()[0][0]
statement = "UPDATE table1 SET juliandate = '%s' WHERE date = '%s'" % (julianDate, fullDate)
curs1.execute(statement)
conn.commit()
else: # for nonleap year
你确定在你的数据库中没有两个相同日期的记录吗?为了使它至少容易出错,你可以给子查询添加一个LIMIT 1 ... – dcn 2011-03-17 20:37:36