How to make a field of a DataBase as array?
I want to have a column in a database that can contain multiple entries. Is it possible to have to define the type of the column as an array (fixed-sized array or some dynamic collection) so that it can store multiple entries开发者_如何学Go.
If you require various values to be stored together, in a single field, then you will likely be best off storing them as a delimiter-separated string of values:
+----------------------------------+ | PRODUCTS | +----------+-----------------------+ | Product | Colors | +----------+-----------------------+ | Notebook | blue,red,green,orange | +----------+-----------------------+
This is usually not what youw want though. Generally-speaking, the idea solution is to create relationships between tables. For instance:
+---------------+ | PRODUCT | +----+----------+ | ID | Product | +----+----------+ | 1 | Notebook | +---------------+ +---------------+ | COLORS | +----+----------+ | ID | Color | +----+----------+ | 1 | Blue | +---------------+ | 2 | Red | +---------------+ | 3 | Green | +---------------+ +---------------------+ | PRODUCTCOLORS | +-----------+---------+ | ProductID | ColorID | +-----------+---------+ | 1 | 1 | Notebook, Blue +-----------+---------+ | 1 | 3 | Notebook, Green +-----------+---------+
yes, in a typical relational design, you would have a 1:N (1-to-many) relationship between 1 table and another. each row in the first table represents a collection, each row in the second table is an element in a collection and references the first table.
a comma-separated list, serialize, or a url-encoded string is also a good solution as the other answers point out...
No, but what server side language are you using?
If using PHP you can use
$serializedArray = serialize($myArray);
And then insert that value into the db. To get it back out use unserialize()
;
This is pretty much the same answer as above (have a delimited string), but you could also save the text in that column as XML. Depending on the database you are using, that could be easy or tedious.
As pointed out above, is you obviously lose any aspect of being able to manage the data integrity from your DB layer (easily).
精彩评论