将SQL查询转换为SQLAlchemy

时间:2018-07-16 13:16:32

标签: mysql sqlalchemy

我想将查询转换为SQLalchemy:

SELECT sel.ID,sel.URL,GROUP_CONCAT(sel.label_values) 
     FROM
        (
         SELECT table1.id as ID, table1.url as URL,CONCAT_WS(':',label 
          ,value) as label_values
         FROM table1 LEFT OUTER JOIN table2 ON table1.id = 
              table2.media_id
         WHERE table1.type = "image" AND table1.id >= 0
         ORDER BY table1.id
         ) AS sel
     GROUP BY sel.ID

我尝试过这样的事情:

label_and_values_column = func.CONCAT_WS(' : ',table2.c.label, 
                 table2.c.value).label(name='label_and_values_column')

outer_join_select = select([table1, label_and_values_column])\
                                       .order_by(table1.c.id)\
                       .select_from(table1.outerjoin(table2))\
                             .label(name='outer_join_select')


all_ = func.group_concat(' : ',outer_join_select.id)\
         .label(name='all_label_and_values_per_media_id')

最后一行给我

Caught exception: Neither 'Label' object nor 'Comparator' object has an attribute 'id'.

我正在将数据库连接用于engine.begin()db_conn_transaction的事务:

meta = sqlalchemy.MetaData(db_conn_transaction)

我想构造select_statment然后使用select_statment.execute().fetchall()

由于我没有.subquery(),因此无法使用session.query()...

欢迎任何在SQLalchemy中转换我的查询的帮助!

0 个答案:

没有答案