在表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