我想合併數據。以下是我的MySQL表。我想用Python遍歷這兩個列表(其中一個用dupe ='x',另一個用null dupes)。如何比較2個列表並將它們合併到Python/MySQL中?
這是示例數據。實際數據是巨大的。
例如:
a b c d e f key dupe
--------------------
1 d c f k l 1 x
2 g h j 1
3 i h u u 2
4 u r t 2 x
從上面的示例表,所需的輸出是:
a b c d e f key dupe
--------------------
2 g c h k j 1
3 i r h u u 2
我到目前爲止有:
import string, os, sys
import MySQLdb
from EncryptedFile import EncryptedFile
enc = EncryptedFile(os.getenv("HOME") + '/.py-encrypted-file')
user = enc.getValue("user")
pw = enc.getValue("pw")
db = MySQLdb.connect(host="127.0.0.1", user=user, passwd=pw,db=user)
cursor = db.cursor()
cursor2 = db.cursor()
cursor.execute("select * from delThisTable where dupe is null")
cursor2.execute("select * from delThisTable where dupe is not null")
result = cursor.fetchall()
result2 = cursor2.fetchall()
for each record
for each field
perform the comparison and perform the necessary updates
### How do I compare the record with same key value and update the original row null field value with the non-null value from the duplicate? Please fill this void...
cursor.close()
cursor2.close()
db.close()
謝謝你們!
想不通的問題。你想獲得algorythm,還是根據具體框架來實現? 事實上,你不需要遍歷遊標和'coalesce'項的字段。 在這種情況下你可以執行普通的SQL嗎?如果可以,原因是查詢很簡單。 – 2010-04-09 20:26:21
這是簡單,簡單的測試數據。實際上,有幾千行和幾百列,因此這種方法。謝謝。 – ThinkCode 2010-04-09 20:33:14
update delthistable t set ta = coalesce(dup.a,ta),tb = coalesce(dup.b,tb)... from(select * from delthistable where dupe ='x')dup 其中t.dupe <>'x'and t.key = dup.key ------------------------------------ -------------------------- 從delthistable刪除其中dupe <>'x' – 2010-04-09 20:51:51