简体   繁体   中英

I have to delete some rows from two tables which are connected with a foreign key on the basis of counts

I have two tables called property and tanks, any property can have one or more than one contacts, in tanks table I have propertyid as foreign key. I want to delete the properties based on the number of tanks. Here is the query which is not working

DELETE  P FROM properties P
LEFT JOIN
(
   SELECT T.Id 
   FROM tanks T 
   GROUP BY T.PropertyID 
   HAVING COUNT(T.ID) = 2
 ) T ON T.PropertyId = P.ID 

Try below query:

DELETE p.* FROM properties p 
JOIN tanks t 
ON p.id=t.property_id 
GROUP BY t.property_id 
HAVING COUNT(t.id)=2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM