[英]UPDATE multiple MySQL rows with different values
Note : I realize this may be confusing taking about tables and columns below so here is a simplified version of the two tables I mention: 注意 :我意识到这可能会使下面的表和列感到困惑,所以这里是我提到的两个表的简化版本:
Table "categories" has columns : id, type 表“categories”包含列 :id,type
Table "entries" has columns : id, categories, ... 表“条目”包含列 :id,categories,...
I have a MySQL table named entries where one of the columns, named categories, is a string of pipe separated indices. 我有一个名为entries的MySQL表,其中一列名为categories,是一串管道分隔的索引。 For example, "|1|2|3|"
例如,“| 1 | 2 | 3 |” might be a possible value and "|1|3|4|"
可能是一个可能的值和“| 1 | 3 | 4 |” could be another.
可能是另一个。 The numbers represent indices of the table categories.
数字代表表类别的索引。
I'm writing an admin script that allows a new row to be inserted into the categories table and when doing this, the appropriate rows of the table entires should have the categories column updated. 我正在编写一个管理脚本,允许将新行插入到类别表中,并且在执行此操作时,表格的相应行应该更新类别列。 For example, if a newly inserted row of the categories table has index 5 then "5|"
例如,如果类别表的新插入行具有索引5,则“5 |” should be concatenated to each appropriate column categories of the entries table.
应该连接到条目表的每个适当的列类别。
I realize that I could could use UPDATE per appropriate entries row when adding a new category but am wondering if there is a better way to go about this. 我意识到在添加新类别时我可以在每个适当的条目行使用UPDATE,但我想知道是否有更好的方法来解决这个问题。 In case this is not clear I know that this is an option but want to know if this can be made into one statement (pseudo-code):
如果不清楚我知道这是一个选项,但想知道这是否可以成为一个语句(伪代码):
foreach ($entriesToUpdate as $currEntry)
"UPDATE entires SET categories='".$currValue."|".$newIndex."' WHERE id=".$currId;
This can be done with an expression-based update: 这可以通过基于表达式的更新来完成:
UPDATE entries SET categories=CONCAT(categories, "5|") WHERE id IN (1,2,3,4,...)
( 5|
instead of 5|
from your example, since your examples seem to show that the existing value will start and end with |
s already.) (
5|
而不是示例中的5|
,因为您的示例似乎表明现有值将以|
s开头和结尾。)
That said, you'd probably be better off with a database schema that stores a mapping of entries to categories in a separate many-to-many table. 也就是说,使用数据库模式可能会更好,该数据库模式在单独的多对多表中存储条目到类别的映射。 For example:
例如:
categories: 类别:
id | type | ...
---------------
1 ...
2 ...
3 ...
entries: 项:
id | ...
---------
100 ...
101 ...
102 ...
entries_to_categories: entries_to_categories:
entry | category
----------------
100 1
100 2
101 3
Then you can use JOINs
to retrieve the set of categories if desired, or check if something is in a category. 然后,您可以根据需要使用
JOINs
来检索类别集,或检查某个类别中是否存在某些内容。 In this case, entry 100
is in categories 1
and 2
, entry 101
is in category 3
, and entry 102
is in no categories. 在这种情况下,条目
100
在类别1
和2
,条目101
在类别3
,条目102
不在类别中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.