Serialize vs Implode

独自空忆成欢 提交于 2019-12-01 10:46:04

I would pefer serialize or JSON-encode.
It is more flexible and for example will allow you to add image title and other details there in future...

If you don't want to (over?)normalize your tables, and you really just want to store a list of ids then I suggest using a simple comma-separated list, because already MySQL has some functions which can directly deal with comma-separated string values:

FIND_IN_SET: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

SELECT FIND_IN_SET('b','a,b,c,d'); --> 2

CONCAT_WS: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws

SELECT CONCAT_WS(',','First name',NULL,'Last Name'); --> 'First name,Last Name'

Of course, you won't be able to do SQL JOINs, but it still can be helpful.

As far as I know there are not significant differences in this case but implode() is a bit faster since it assumes an array and serialize() does not know what you are passing to it.

EDIT based on OP's comment:

Well all the images are stored in a seperate library table with the title and descriptions and things like that. But yeah I see your point.

In that case is not a good idea so serialize several IDs into a single field. What you need is a *-to-Many relation between your 2 tables. This is the correct way of represent multivalued fields:

+----------------------+
|  USER                |
+---------+------+-----+
| user_id | name | ... |
+---------+------+-----+

+----------------------+
|  USER_PICTURE        |
+---------+------------+
| user_id | picture_id |
+---------+------------+

+--------------------------+
|  PICTURE                 |
+------------+-------+-----+
| picture_id | title | ... |
+------------+-------+-----+

My friend, serialization is to obtain a string representation of an object's status. Even if it works i don't think is the best way to do what you want. I would prefer to store a json object with the ids. Because a json object is multiplatform, is a string and is easily readable by a human i think is a good approach.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!