无法将此SQL字符串(使用VALUES ... AS)转换为SQLAlchemy代码

时间:2018-05-08 15:20:57

标签: python sql sqlalchemy

我拥有的SQL查询可以从它们连接在一起的3个表中识别Max编辑时间:

Select Identity.SSN, Schedule.First_Class, Students.Last_Name,
(SELECT Max(v)
    FROM (VALUES (Students.Edit_DtTm), (Schedule.Edit_DtTm),
    (Identity.Edit_DtTm)) AS value(v)) as [MaxEditDate]
FROM Schedule
LEFT JOIN Students ON Schedule.stdnt_id=Students.Student_Id
LEFT JOIN Identity ON Schedule.std_id=Identity.std_id

我需要将它放在SQLAlchemy中,以便我可以引用代码中其他地方使用的列。以下是我尝试做的最简单的版本,但它不起作用。我尝试过改变查询的方式,但是我得到了一个SQL错误,我错误地使用VALUES或者它没有正确加入并获得了那些实际的最高价值列没有将它与外部查询匹配

max_edit_subquery = sa.func.values(Students.Edit_DtTm, Schedule.Edit_DtTm, Identity.Edit_DtTm)
base_query = (sa.select([Identity.SSN, Schedule.First_Class, Students.Last_Name,
                            (sa.select([sa.func.max(self.max_edit_subquery)]))]).
                            select_from(Schedule.__table__.join(Students, Schedule.stdnt_id == Students.stdnt_id).
                            join(Ident, Schedule.std_id == Identity.std_id)))

2 个答案:

答案 0 :(得分:1)

我不是SQLAlchemy的专家,但您可以与VALUES交换UNION ALL

Select Identity.SSN, Schedule.First_Class, Students.Last_Name,
(SELECT Max(v)
    FROM (SELECT Students.Edit_DtTm AS v
         UNION ALL SELECT Schedule.Edit_DtTm
         UNION ALL SELECT Identity.Edit_DtTm) s
   ) as [MaxEditDate]
FROM Schedule
LEFT JOIN Students ON Schedule.stdnt_id=Students.Student_Id
LEFT JOIN Identity ON Schedule.std_id=Identity.std_id;

另一种方法是使用GREATEST函数(在T-SQL中不可用):

Select Identity.SSN, Schedule.First_Class, Students.Last_Name,
    GREATEST(Students.Edit_DtTm, Schedule.Edit_DtTm,Identity.Edit_DtTm)
    as [MaxEditDate]
FROM Schedule
LEFT JOIN Students ON Schedule.stdnt_id=Students.Student_Id
LEFT JOIN Identity ON Schedule.std_id=Identity.std_id;

我希望它能帮助您将其翻译成ORM版本。

答案 1 :(得分:0)

我有类似的问题,我使用以下方法解决了。我已经添加了完整的代码和结果查询。该代码已在MSSQL服务器上执行。我使用了不同的表,并在下面的代码片段中用了您需要的表和列。

from sqlalchemy import *
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.types import String
from sqlalchemy.sql.expression import FromClause


class values(FromClause):
    def __init__(self, *args):
        self.column_names = args


@compiles(values)
def compile_values(element, compiler, asfrom=False, **kwrgs):
    values = "VALUES %s" % ", ".join("(%s)" % compiler.render_literal_value(elem, String()) for elem in element.column_names)
    if asfrom:
        values = "(%s)" % values
    return values


base_query = self.db_session.query(Schedule.Edit_DtTm.label("Schedule_Edit_DtTm"),
                                 Identity.Edit_DtTm.label("Identity_Edit_DtTm"),        
                                 Students.Edit_DtTm.label("Students_Edit_DtTm"),
                                 Identity.SSN                            
                                 ).outerjoin(Students, Schedule.stdnt_id==Students.Student_Id
                                 ).outerjoin(Identity, Schedule.std_id==Identity.std_id).subquery()

values_at_from_clause = values(("Students_Edit_DtTm"), ("Schedule_Edit_DtTm"), ("Identity_Edit_DtTm")
                                ).alias('values(MaxEditDate)')

get_max_from_values = self.db_session.query(func.max(text('MaxEditDate'))
                                            ).select_from(values_at_from_clause)

output_query = self.db_session.query(get_max_from_values.subquery()
                                     ).label("MaxEditDate")

**print output_query**


SELECT
    anon_1.Schedule_Edit_DtTm AS anon_1_Schedule_Edit_DtTm,
    anon_1.Students_Edit_DtTm AS anon_1_Students_Edit_DtTm,
    anon_1.Identity_Edit_DtTm AS anon_1_Identity_Edit_DtTm,
    anon_1.SSN AS anon_1_SSN
    (
        SELECT
            anon_2.max_1
        FROM
            (
                SELECT
                    max( MaxEditDate ) AS max_1
                FROM
                    (
                    VALUES (Students_Edit_DtTm),
                           (Schedule_Edit_DtTm),
                           (Identity_Edit_DtTm)
                       ) AS values(MaxEditDate)
            ) AS anon_2
    ) AS MaxEditDate
FROM
    (
        SELECT
            Schedule.Edit_DtTm AS Schedule_Edit_DtTm,
            Students.Edit_DtTm AS Students_Edit_DtTm,
            Identity.Edit_DtTm AS Identity_Edit_DtTm,
            Identity.SSN AS SSN
        FROM
            Schedule WITH(NOLOCK)
        LEFT JOIN Students WITH(NOLOCK) ON
            Schedule.stdnt_id==Students.Student_Id
        LEFT JOIN Identity WITH(NOLOCK) ON
            Schedule.std_id==Identity.std_id
    ) AS anon_1