Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

python - SQLAlchemy: How to Delete with join

I have trouble doing such thing bottom with SQLAlchemy:

DELETE a FROM a INNER JOIN b ON b.`aId` = a.`Id` WHERE `b`.`xxx` = ?;

As the post here: SQLAlchemy: Create delete query using self-join on MySQL

I've got it's hard to do delete in SQLAlchemy with join.

So I'm now doing like this:

session.execute('DELETE a FROM a INNER JOIN b ON b.`aId` = a.`Id` WHERE `b`.`xxx` = %d;'%xxx)

But it just annoy me a lot like about: SQL Injection thing, etc..

Is there any way using SQLAlchemy to solve the problem here? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the way I did it:

map_ids = session.query(Table1.map_id). 
    filter(Table1.xxxx == 'xxx_value')

q = session.query(Table2). 
    filter(Table2.map_id.in_(map_ids.subquery()))

q.delete(synchronize_session=False)

The key here are you create subquery by finding ids that has to be deleted. Then you use 'in_' operator to select records to be deleted. 'synchoronize_session=False' will execute query without updating session. This gives the best performance boost.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...