简体   繁体   中英

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

Table "entries" has columns : id, categories, ...

I have a MySQL table named entries where one of the columns, named categories, is a string of pipe separated indices. For example, "|1|2|3|" might be a possible value and "|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|" 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. 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.)


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:

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. In this case, entry 100 is in categories 1 and 2 , entry 101 is in category 3 , and entry 102 is in no categories.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM