一次性更新多对多连接器表

发布于 2024-10-26 17:01:17 字数 446 浏览 7 评论 0原文

假设我有两个表:

articles
categories

有一个多对多的表连接它们。

CREATE TABLE cat2art (
  article_id INT,
  category_id INT
);

对于特定的文章,我有一个类别 ID 的“新列表”,我们需要用这些更新 cat2art 表。

一些类别被删除,一些类别被添加,一些类别保持原样。更新此表的最有效方法是什么?

我可以天真地删除具有指定的article_id的所有记录,然后简单地再次添加它们。但是,如果我要在跟踪文章链接到类别的同一个表中记录日期,那么该信息现在将被销毁。

我正在寻找一种可以轻松解决此问题的出色模式。这个问题专门针对 PHP 和 MySQL,但其他语言的答案也可以,只要它们也适用于 PHP+MySQL。

Say I have two tables:

articles
categories

There's a many to many table that connects them.

CREATE TABLE cat2art (
  article_id INT,
  category_id INT
);

For a specific article, I have a 'new list' of category id's, and we need to update the cat2art table with these.

Some categories got removed, some got added and some stayed where they were. What is the most effective way to update this table?

I could naively delete all records with the specified article_id and simply add them again. However, if I were to record a date in that same table that tracks when an article was linked to a category, that information will now be destroyed.

I'm looking for a great pattern that easily solves this issue. This question is specifically for PHP and MySQL, but answers in other languages are also fine provided they are applicable to PHP+MySQL as well.

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

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

发布评论

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

评论(2

怪我入戏太深 2024-11-02 17:01:17

其他系统支持 MERGE 语句,它可以完全满足您的需求。

但是,在 MySQL 中,您至少需要两个查询(它不能在单个语句中删除和插入/更新):

DELETE
FROM    cat2art
WHERE   art_id = $art_id
        AND cat_id NOT IN ($new_cat_1, $new_cat_2, …);

INSERT
IGNORE
INTO    cat2art
VALUES
($art_id, $new_cat_1),
($art_id, $new_cat_2),
…;

Other systems support MERGE statement which would do exactly what you want.

However, in MySQL, you would need at least two queries (it cannot delete and insert/update in a single statement):

DELETE
FROM    cat2art
WHERE   art_id = $art_id
        AND cat_id NOT IN ($new_cat_1, $new_cat_2, …);

INSERT
IGNORE
INTO    cat2art
VALUES
($art_id, $new_cat_1),
($art_id, $new_cat_2),
…;
起风了 2024-11-02 17:01:17

您可以将 (article_id,category_id) 定义为唯一键,并在插入连接时使用 INSERT IGNORE 语法。这样,如果此连接已经存在,则不会再次添加它,也不会更新现有记录,并且 create_date 列保持不变。

例子:

INSERT IGNORE INTO cat2art (article_id, category_id, create_date) 
VALUES(100,200,NOW());

You can define (article_id, category_id) as unique key, and when inserting a connection use INSERT IGNORE syntax. That way if this connection already exists it will not be added again, nor will it update the existing record, and the create_date column stays untouched.

example:

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