pypika icon indicating copy to clipboard operation
pypika copied to clipboard

How do I use MySQL DELETE with JOIN?

Open dashmug opened this issue 5 years ago • 4 comments
trafficstars

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?

dashmug avatar Jul 16 '20 08:07 dashmug

This is what I was trying to achieve: https://stackoverflow.com/questions/652770/delete-with-join-in-mysql

dashmug avatar Jul 16 '20 17:07 dashmug

Does not seem to be supported. I tried this just today as well, but found no solution.

malun22 avatar Mar 15 '22 15:03 malun22

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?

raxod502 avatar May 23 '22 03:05 raxod502

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.

raxod502 avatar May 23 '22 03:05 raxod502