|How to define an array in sql?|
| 11:19 am on Jun 29, 2011 (gmt 0)|
I need to store an array of numbers (22,22,33,44,etc) in my database.. but what data type and (special?) attributes i have to set for this?
I googled but didn't find an answer..
Please help me, thanks!
| 4:02 pm on Jun 29, 2011 (gmt 0)|
You **could** use varchar. But something tells me you are likely to use programming operations on these - splitting up the array **after** reading in. A more efficient way would be to use a second table and joins:
select main_table.title as title,array_table.array_member as member where main_table.id=array_table.record_id order by main_table.title asc, array_table.array_member.asc
Then in the while loop, print out title|member
Note a group by is not needed with the ordering. This should give you
If you use this approach, you can store your numbers as int fields, which would be much faster - it would also allow you to leverage the power of mysql searches. With the varchar method you'd have to resort to (unnecessarily) complicated regexps. Instead you can do
select main_table.title as title,array_table.array_member where main_table.id=array_table.record_id and array_table.array_member = 22
You can also explore left, right, and inner joins if there are null values (no records in the joined table), etc - all of which you can't do storing a comma-separated list of values. Faster results, more possibilities.
|brotherhood of LAN|
| 4:07 pm on Jun 29, 2011 (gmt 0)|
Going with rocknbil's suggestion of another table, you could use the GROUP_CONCAT [dev.mysql.com] function to group all the int values alongside the 'main table' record.
However, if you are only using a small set of numbers (64 or less), the SET Type [dev.mysql.com] may be a good option to you.