Python 如何构建;删除“中存在的内容”;使用炼金术?
我想从具有复合键的表中删除行 我需要构造表单的查询:Python 如何构建;删除“中存在的内容”;使用炼金术?,python,sql,sqlalchemy,Python,Sql,Sqlalchemy,我想从具有复合键的表中删除行 我需要构造表单的查询: 从(子查询)中存在(c1、c2、c3)的t中删除 我怎样才能在炼金术中做到这一点 下面是一个示例,其中有一个表记录了每个用户每场游戏的多个分数。我想删除用户参与的每个游戏中每个用户的最低分数 来自sqlalchemy导入表、列、元数据、字符串、整数 元数据=元数据() t=表('分数'),元数据, 列('游戏',字符串), 列('user',字符串), 列('分数',整数)) 数据可能如下所示: game user scor
从(子查询)中存在(c1、c2、c3)的t中删除
我怎样才能在炼金术中做到这一点
下面是一个示例,其中有一个表记录了每个用户每场游戏的多个分数。我想删除用户参与的每个游戏中每个用户的最低分数
来自sqlalchemy导入表、列、元数据、字符串、整数
元数据=元数据()
t=表('分数'),元数据,
列('游戏',字符串),
列('user',字符串),
列('分数',整数))
数据可能如下所示:
game user score
g1 u1 44
g1 u1 33
g1 u1 2 (delete this)
g2 u1 55
g2 u1 1 (and this)
我想删除(g1,u1,2)
和(g2,u1,1)
以下是我迄今为止使用SQLAlchemy的尝试:
from sqlalchemy import delete, select, func, exists, tuple_
selector_tuple = tuple_(t.c.game, t.c.user, t.c.score)
low_score_subquery = select([t.c.game, t.c.user, func.min(t.c.score)])\
.group_by(t.c.game, t.c.user)
in_clause = selector_tuple.in_(low_score_subquery)
print "lowscores = ", low_score_subquery # prints expected SQL
print "****"
print "in_clause = ", in_clause # prints expected SQL
虽然我在_子句和低分_子查询中得到了预期的SQL,但删除查询(下面)是不正确的。我尝试过以下几种方法,但结果都很糟糕:
>>> delete_query = delete(t, exists([t.c.game, t.c.user, t.c.score],
... low_score_subquery))
>>> print delete_query # PRODUCES INVALID SQL
DELETE FROM scores WHERE EXISTS (SELECT scores."game", scores."user", scores.score
FROM (SELECT scores."game" AS "game", scores."user" AS "user", min(scores.score) AS min_1
FROM scores GROUP BY scores."game", scores."user")
WHERE (SELECT scores."game", scores."user", min(scores.score) AS min_1
FROM scores GROUP BY scores."game", scores."user"))
我试过
存在(在_子句中)
,存在([],在_子句中)
和在_子句中。存在()
,但这些都会导致异常 你真的需要这个存在吗?这不是你想要的吗
>>> delete_query = delete(t, in_clause)
>>> print(delete_query)
DELETE FROM scores WHERE (scores.game, scores."user", scores.score) IN (SELECT scores.game, scores."user", min(scores.score) AS min_1
FROM scores GROUP BY scores.game, scores."user")