pypika
pypika copied to clipboard
How do I use MySQL DELETE with JOIN?
I have the following PyPika code:
from pypika import MySQLQuery, Parameter, Table
table1 = Table("Table_1")
table2 = Table("Table_2")
table3 = Table("Table_3")
print(
MySQLQuery.from_(table1)
.delete()
.inner_join(table2)
.on(table2.id.eq(table1.table2_id))
.inner_join(table3)
.on(table3.id.eq(table2.table3_id))
.where(table3.id.eq(Parameter("%s")))
)
It gives the following MySQL code (linebreaks added for readability).
DELETE
FROM `Table_1`
JOIN `Table_2` ON `Table_2`.`id`=`Table_1`.`table2_id`
JOIN `Table_3` ON `Table_3`.`id`=`Table_2`.`table3_id`
WHERE `Table_3`.`id`=%s
which fails.
The correct SQL code should have been
DELETE `Table_1`
FROM `Table_1`
JOIN `Table_2` ON `Table_2`.`id`=`Table_1`.`table2_id`
JOIN `Table_3` ON `Table_3`.`id`=`Table_2`.`table3_id`
WHERE `Table_3`.`id`=%s
How do I do this in PyPika?
This is what I was trying to achieve: https://stackoverflow.com/questions/652770/delete-with-join-in-mysql
Does not seem to be supported. I tried this just today as well, but found no solution.
Is there a workaround where we can inject the raw SQL for the table name into the query? Does PyPika support such extensions? Or do we have to drop the library altogether?
Seems that there is a partial workaround (works on Postgres only?) where you can DELETE FROM ... USING instead of DELETE FROM ... INNER JOIN: https://github.com/kayak/pypika/issues/397. Works for my use case, but I don't think it's an acceptable solution.