开发者

What's faster? "explode" or another column?

I have a situation where I need to have multiple values stored in my database but they are approx. same type so now I don't know is it faster to store those values as a String in VARCHAR field in MySQL separated with commas

1,2,3,4,5

and then explode them every them I need them

$values = explode(",", $string开发者_StackOverflowFromDatabase);

where $stringFromDatabase is String from mysql_query + mysql_fetch_array and get them one by one with $values[0], $values[1] and so on

OR

Add another columns for every variable (max. 7 rows) and then call the database for specific row and just get them individually by columns with standard mysql_query + mysql_fetch_array procedure?

So, one column concatenated with commmas or multiple columns? Important to notice, I always need them all (one by one ofcourse) and sorting is not important - so I think that the first option - is the better, faster one?


Its better to have multiple columns. It part of database normalization not to have multivalued columns.

In your case - what if you needed to select the "3" on from the multivalued 1,2,3,4,5? It would be quite challenging. But with multiple columns I can easily do SELECT * FROM Table Where Column3 = 3.


General rule of thumb with databases is that columns should be atomic. In other words, they should represent one piece of information and only one. Cramming a CSV list into a column breaks this principle and can make life harder for you in the long run, especially when it comes to doing analytics on the data you have stored. I'd suggest that having one column per value would be the best bet.


Use a separate column for each value. See 1NF


You shouldn't ask "which is faster".
Speed is not the only thing to take into account. A space rocket is indeed faster than your family car, but you don't drive to the mall on a rocket.
So, you should ask "what way is proper one" instead.
And to normalize your database is the only proper way.


what about using something like:

int AutoId, // your primary key
int ColumnIndex // 1 for col 1
int ColumnValue // the value for e.g. for col 1

this does not need space for unused columns and gives the benefit to query like

select ColumIndex, ColumnValue where AutoID = 42 order by ColumnIndex
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜