0

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?

1
  • 1
    Normalizing your data would make this unnecessary and your life a lot easier Commented Jul 27, 2012 at 2:02

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, so this would be a good place to use a unique index, right?
Yes, both of the id columns should be declared as PRIMARY KEY, which enforces a unique constraint. The declaration might look like this: id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY
0

Either

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.