如何在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
匹配SERVICE
表中<{1}}的所有记录
答案 0 :(得分:1)
您可以先在SERVICE=122
上分别捕捉过滤器;我假设您使用camelcase为所有与表名匹配的表都有模型。
还会存储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_
method,将后者转换为子选择,以生成如下查询:
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
。