delete from 3 tables with one query

感情迁移 提交于 2019-12-10 15:14:40

问题


i have 3 tables and i dont want define any foreign key in my tables. my tables structure are like below: tables diagram

i have written this query :

delete relativedata, crawls, stored
    from relativedata inner join
         crawls
         on relativedata.crawl_id = crawls.id and
            relativedata.id = ? inner join
         stored
         on stored.crawl_id = crawls.id

this query works for me unless one of tables has no records. now how can i do this delete in 3 tables in 1 query?


回答1:


If it works if all tables have records, try using LEFT JOIN instread of INNER JOIN. Also, You had some mess with Your joins ON conditions. Try it like this:

delete 
    relativedata, crawls, stored
from
    relativedata 
LEFT join crawls on relativedata.crawl_id = crawls.id
LEFT join stored on relativedata.crawl_id = stored.crawl_id
WHERE
    relativedata.id = ? 

Also, foregin keys are good thing, and not using them is generally bad idea. Yes, they seems to be annoying at first, but try to focus on WHEN they annoy You. Most of the times they do it when You are meddling with data in a way You should not, and without them You wloud cause data incostincency in Your DB.

But, it is just my opinion.



来源:https://stackoverflow.com/questions/34577603/delete-from-3-tables-with-one-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!