原始SQL到sqlalchemy语法

时间:2016-12-05 17:52:54

标签: python mysql sql-server sqlalchemy

我正在使用sqlaclhemy在我的python项目中查询我的数据库,我对sqlalchemy很新,但是就像目前的概念一样,我做的很简单,比如,

sel = select([staff.c.name]) \
    .select_from(staff) \
    .where(staff.c.workbase != "") \
    .where((staff.c.status != 'Left') & (staff.c.status != 'Name Changed'))

我的项目的一部分需要更复杂的SQL查询,但我想将它保存在sqlalchemy中,我的原始sql看起来像这样,

    SELECT A.a_allowance, B.b_allowance, C.c_allowance, A.name, A.leave_allowance
FROM
    (SELECT ROUND(leave_allowance * 0.32, 2) as a_allowance, name, leave_allowance FROM staff_list) A
    INNER JOIN
    (SELECT ROUND(leave_allowance * 0.40, 2) as b_allowance, name FROM staff_list) B
    ON A.name = B.name
    INNER JOIN
    (SELECT ROUND(leave_allowance * 0.28, 2) as c_allowance, name FROM staff_list) C
    ON A.name = C.name
    WHERE A.name = 'Jones Jones';

我不确定如何在sqlalchemy中执行嵌套选择等。

1 个答案:

答案 0 :(得分:1)

您可以使用.join()生成联接:

>>> print(foo.join(bar, foo.c.bar_id == bar.c.id))
foo JOIN bar ON foo.bar_id = bar.id

您可以通过子查询替换表达式中的表名:

>>> left = select([foo.c.bar_id]).select_from(foo).where(foo.c.baz > 0).alias("left")
>>> print(left.join(bar, left.c.bar_id == bar.c.id))
(SELECT foo.bar_id AS bar_id 
FROM foo 
WHERE foo.baz > :baz_1) AS "left" JOIN bar ON "left".bar_id = bar.id

在大多数情况下,子查询的行为与表格完全相同。