如何从多个表中选择两列

0 投票
1 回答
2676 浏览
提问于 2025-04-18 04:54

我想用 psycopg 从多个表中选择两列。虽然用连接(join)或者并集(union)可能也能实现这个目的,但我想找一种可以一次读取更多表的方法。

我的想法是先获取表的列表,然后用循环依次读取每个表。不过,这样做不太奏效。有没有其他的建议或者想法呢?

这是我的代码。

try:
    con = psycopg2.connect(database='****', user='****', password = '****', host='****', port = ****)
    con.autocommit = True
    cur = con.cursor()
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name ASC;")
    tablename=cur.fetchall()


    for x in tablename:
        cur.execute("SELECT column1, column2 FROM %s ORDER BY column1 ASC", (x))
        mytest = cur.fetchall()

except psycopg2.DatabaseError, e:
if con: 
    con.rollback()

print 'Error %s' % e    
sys.exit(1)


finally: 

if con:
        con.close()

这是错误信息。

Error syntax error at or near "'table1'"

LINE 1: SELECT column1, column2 FROM 'table1' ORDER BY ...

                                 ^

1 个回答

0

抱歉!是我搞错了!我找到了解决办法。

在PostgreSQL代码中,Python字符串应该是完全清晰的,不要有任何格式,比如不需要用""或''来替代字符串。

这是修改后的代码。

try:
    con = psycopg2.connect(database='****', user='****', password = '****', host='****', port = ****)
    con.autocommit = True
    cur = con.cursor()
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name ASC;")
    tablename=cur.fetchall()


    for x in tablename:
        for y in x:
            cur.execute("SELECT column1, column2 FROM {mytable} ORDER BY column1 ASC". format(mytable=y))
            mytest = cur.fetchall()

except psycopg2.DatabaseError, e:
    if con: 
        con.rollback()

    print 'Error %s' % e    
    sys.exit(1)


finally: 

    if con:
            con.close() 

再次感谢你的帮助!

撰写回答