I’m creating a search function for my website, and i’ve therefore taken keywords from the main table, and summarized these as keys in a secondary table linking to the main table via id.
My setup looks like this:
—————————————————–
| ITEMS |
—————————————————–
| Id | Name | Price |
—————————————————–
| 1 | CPU | 199.95 |
| 2 | GPU | 249.95 |
| 3 | GPU | 225.95 |
—————————————————–
—————————————————–
| KEYS |
—————————————————–
| Id | item_name | item_id |
—————————————————–
| 1 | CPU | 1 |
| 2 | GPU | 2 |
| 3 | GPU | 3 |
—————————————————–
Bear in mind my table is more complex, generating many keys for each row.
My problem is that if there are a lot of duplicate keywords, the keywords table becomes very large. My question is therefore:
Is it possible to somehow group the id’s in mySQL for each unique item_name so if someone searches for GPU the out put will be 2 and 3?
I’m thinking you can separate the values in a string using eg. a comma like so:
—————————————————–
| 2 | GPU | 2,3 |
—————————————————–
However I feel it gets complicated when for instance an item in items is deleted and I need to update my keys table and maybe remove an Id=5 from the string “1,3,5,7,10,15”…
Is there a smart way of linking same name keys to multiple entries? Or will I always need a regular expression, and maybe even PHP, to separate the values?
Do not use CSV in a database table, but use a join instead to select the data.
You should be able to generate the output like so:
The
group_concatwill generate the CSV on the fly, so you don’t have to store CSV in the database.If you need more than one row of output, you can use a
group byclause.See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Note that this has nothing to do with regex.