wecsam
wecsam

Reputation: 2751

Variable-Length Array in MySQL

I'm writing an application in PHP that uses a MySQL database to store information. One of the pieces of information that it has to store is an array of names, but the array has no set length. It could range from one to many items. Is there a way to store this array in MySQL and be able to retrieve it by specifying just one item from the array?

For example, I want to be able to store something like this in a table:

Foo        Bar
-------------------
[baz,car]  fiz
[abc,def]  ghi

Then, I want to be able to tell MySQL just to search for car and SELECT the first row in the table above.

Is there a feasible way to implement this?

Upvotes: 0

Views: 2184

Answers (2)

Chris Trahey
Chris Trahey

Reputation: 18290

The way to implement it is to "normalized" the schema. There are several related ideas which comprise schema normalization, but the critical one here is that your data should be represented with two tables and a relationship between. The relationship is called, "one to many", since for one "Bar" there are one-or-more "Foo".

A necessary step, then, is to add unique identifier columns to your schema (easiest just to use auto-incrementing integers), and then query using the JOIN mechanism to relate your data.

this is why we call MySQL (and many others) a "relational" database.

Bar
+----+----------+
| id |   name   | 
+----+----------+
| 01 |   fiz    |
+----+----------+
| 02 |   ghi    |
+----+----------+


Foo
+----+--------+----------+
| id | bar_id |   name   | 
+----+--------+----------+
| 01 |   01   |  baz     |
+----+--------+----------+
| 02 |   01   |  car     |
+----+--------+----------+
| 03 |   02   |  abc     |
+----+--------+----------+
| 04 |   03   |  def     |
+----+--------+----------+

And here is what the join looks like to select the "fiz" record based on "car" in the Foo relation

SELECT 
  Bar.* 
FROM Bar 
  JOIN Foo ON Bar.id = Foo.bar_id 
WHERE Foo.name = "car"

And if you want the entire list of Foo relations for each bar with a matching Foo:

SELECT 
  Bar.*, 
  GROUP_CONCAT(Foo.name) 
FROM Bar 
  JOIN Foo ON Bar.id = Foo.bar_id 
WHERE Foo.name = "car" 
GROUP BY Bar.id

Upvotes: 2

sel
sel

Reputation: 4957

Either

SELECT Bar FROM tbl
WHERE FIND_IN_SET('car', Foo)

Upvotes: 0

Related Questions