2013-05-27 31 views
0

我在PostGresSql中有一個簡單的查詢,我需要將其轉換爲SQLAlchemy。將PostGresSQL轉換爲SqlAlchemy查詢

session.query(table1.name 
       ,table2.ip 
       ,table2.info).distinct().join(table2).group_by(table1.name) 

是否有人可以幫我這個:

SELECT table1.name,table2.ip,table2.info 
FROM table1 LEFT OUTER JOIN table2 
ON(table1.name=table2.hostname) 
GROUP BY table1.name; 

我已經使用這個沒有成功試過嗎?

在此先感謝 Ishwar

回答

0

我想通了回答。我其實是缺少ON狀態查詢:

session.query(table1.name ,table2.ip ,table2.info ).distinct()外連接(表2,table1.name = table2.hostname ).group_by(table1.name)

感謝您的幫助!

0

這不是從你的回答是什麼問題不清楚,但我在此查詢的拍攝將是:

session.query(table1.name 
      ,table2.ip 
      ,table2.info)\ 
     .outerjoin(table2)\ 
     .group_by(table1.name) 
1

這裏是你將如何使用表達式API做

http://docs.sqlalchemy.org/en/latest/core/expression_api.html

  1. 定義你的表,例如:

    table1 = table('table1', 
        column('name', String()) 
    ) 
    
    table2 = table('table2', 
        column('ip', String()), 
        column('info', String()), 
        column('hostname', String()), 
    ) 
    
  2. 撰寫的查詢,如:

    my_query = select([table1.c.name, 
            table2.c.ip, 
            table2.c.info] 
          ).select_from(
            table1.outerjoin(table2, table1.c.name == table2.c.hostname) 
          ).group_by(table1.c.name) 
    
  3. 執行查詢,如:

    db.execute(my_query) 
    
+0

雖然它沒有完全回答問題,但我有一個方向前進。謝謝 – Ishwar