如何重构这个多表删除语句

发布于 2024-09-07 07:46:39 字数 398 浏览 9 评论 0原文

任何人都可以建议一种更干净的方法来删除一个查询中具有一对多关系的行吗?

这是可行的,但我对 using 子句或 delete 不太熟悉,所以我不完全理解它是如何工作的。

DELETE FROM ip_record,
            entry using ip_record 
            inner join entry 
      where ip_record.site_id = ? 
        and ip_record.ip = ? 
        and ip_record.id = entry.ip_id

我有一个想法,这可以通过级联更干净地完成,但我对约束有一种非理性的恐惧。数据库是MySQL。

Can anyone suggest a cleaner method to delete rows with a one-to-many relationship in one query?

This works, but I'm not very familiar with the using clause or delete, so I don't fully understand how it works.

DELETE FROM ip_record,
            entry using ip_record 
            inner join entry 
      where ip_record.site_id = ? 
        and ip_record.ip = ? 
        and ip_record.id = entry.ip_id

I have a notion that this could be done more cleanly with a cascade, but I have an irrational fear of constraints. The DB is MySQL.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贱人配狗天长地久 2024-09-14 07:46:39

是的,按如下方式添加约束

ALTER TABLE entry
    ADD CONSTRAINT constr_entry_fk_ip
    FOREIGN KEY fk_ip (ip_id) REFERENCES ip_record (id)
    ON DELETE CASCADE ON UPDATE CASCADE

,然后您就可以用来

DELETE FROM ip_record
WHERE ip_record.site_id=? and ip_record.ip=?

执行之前需要连接的操作。

Yes, add the constraint as follows

ALTER TABLE entry
    ADD CONSTRAINT constr_entry_fk_ip
    FOREIGN KEY fk_ip (ip_id) REFERENCES ip_record (id)
    ON DELETE CASCADE ON UPDATE CASCADE

and then you can just use

DELETE FROM ip_record
WHERE ip_record.site_id=? and ip_record.ip=?

to do what previously required a join.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文