I am trying to delete from a few tables at once. I've done a bit of research, and came up with this
DELETE FROM `pets` p,
`pets_activities` pa
WHERE p.`order` > :order
AND p.`pet_id` = :pet_id
AND pa.`id` = p.`pet_id`
However, I am getting this error
Uncaught Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'p,
pets_activities
pa...
I've never done a cross table delete before, so I'm inexperienced and stuck for now!
What am I doing wrong?
Use a
JOIN
in theDELETE
statement.Alternatively you can use...
...to delete only from pets_activities
See http://dev.mysql.com/doc/refman/5.0/en/delete.html
For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS, NOT EXISTS, IN, NOT IN, etc. But the one above where you specify from which tables to delete with an alias before the FROM clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.
To anyone reading this in 2017, this is how I've done something similar.
Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.
Since this appears to be a simple parent/child relationship between
pets
andpets_activities
, you would be better off creating your foreign key constraint with a deleting cascade.That way, when a
pets
row is deleted, thepets_activities
rows associated with it are automatically deleted as well.Then your query becomes a simple:
I don't have a mysql database to test on at the moment, but have you tried specifying what to delete prior to the from clause? For example:
I think the syntax you used is limited to newer versions of mysql.
The syntax looks right to me ... try to change it to use INNER JOIN ...
Have a look at this: http://www.electrictoolbox.com/article/mysql/cross-table-delete/
Use this
or