0

如何在 sqlalchemy orm 中编写表达以下查询?

DELETE FROM ACCESS_STRING_DETAILS WHERE MENU_ID IN(SELECT MENU_ID FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM TIME_DETAILS WHERE MENU_ID IN(SELECT MENU_ID FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM REDIRECTOR_INPUT_PARAMS WHERE COMMAND_ID IN(SELECT KEYWORD FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM REDIRECTOR_COMMANDS WHERE COMMAND_ID IN(SELECT KEYWORD FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM RANGE_DETAILS WHERE COMMAND_ID IN(SELECT KEYWORD FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM CLIENT_RSP_DETAILS WHERE KEYWORD IN(SELECT KEYWORD FROM REDIRECTOR WHERE SERVICE=122)
DELETE FROM REDIRECTOR WHERE SERVICE=122

我基本上需要的是从表中删除所有匹配的记录以及表MENU_ID中 的特定KEYWORD记录SERVICEREDIRECTOR

4

1 回答 1

1

SERVICE=122您可以先单独捕​​获过滤器;我假设您有所有与表名匹配的表的模型,使用驼峰命名法。

menu_id 和关键字选择也被存储以供重用:

service_filter = Redirector.service == 122
menu_id_select = session.query(Redirector.menu_id).filter(service_filter)
keyword_select = session.query(Redirector.keyword).filter(service_filter)

现在您可以将这些选择应用于所有删除查询:

(session
    .query(AccessStringDetails)
    .filter(AccessStringDetails.menu_id.in_(menu_id_select))
    .delete(False))
(session
    .query(TimeDetails)
    .filter(TimeDetails.menu_id.in_(menu_id_select))
    .delete(False))
(session
    .query(RedirectorInputParams)
    .filter(RedirectorInputParams.command_id.in_(keyword_select))
    .delete(False))
# etc.

session.query(Redirector).filter(service_filter).delete(False)

这些示例使用带有 select 语句的Column.in_方法,将后者转换为子选择,以生成如下查询:

DELETE FROM access_string_details WHERE access_string_details.menu_id IN (SELECT redirector.menu_id AS redirector_menu_id 
FROM redirector 
WHERE redirector.service = :service_1)

:service_1参数设置为122.

于 2013-03-12T12:29:27.847 回答