一次性更新多对多连接器表
假设我有两个表:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其他系统支持 MERGE 语句,它可以完全满足您的需求。
但是,在 MySQL 中,您至少需要两个查询(它不能在单个语句中删除和插入/更新):
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):您可以将 (article_id,category_id) 定义为唯一键,并在插入连接时使用
INSERT IGNORE
语法。这样,如果此连接已经存在,则不会再次添加它,也不会更新现有记录,并且 create_date 列保持不变。例子:
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: