Efficient method of finding database rows that have *one or more* qualities from a list of seven qualities
Posted
by
hithere
on Stack Overflow
See other posts from Stack Overflow
or by hithere
Published on 2011-01-14T00:45:30Z
Indexed on
2011/01/14
0:53 UTC
Read the original article
Hit count: 151
Hello!
For this question, I'm looking to see if anyone has a better idea of how to implement what I'm currently planning on implementing (below):
I'm keeping track of a set of images, using a database. Each image is represented by one row.
I want to be able to search for images, using a number of different search parameters. One of these parameters involves a search-by-color option. (The rest of the search stuff is currently working fine.)
Images in this database can contain up to seven colors:
-Red
-Orange
-Yellow
-Green
-Blue
-Indigo
-Violet
Here are some example user queries:
"I want an image that contains red."
"I want an image that contains red and blue."
"I want an image that contains yellow and violet."
"I want an image that contains red, orange, yellow, green, blue, indigo and violet."
And so on. Users make this selection through the use of checkboxes in an html form. They can check zero checkboxes, all seven, and anything in between.
I'm curious to hear what people think would be the most efficient way to perform this database search.
I have two possible options right now, but I feel like there must be something better that I'm not thinking of.
(Option 1)
-For each row, simply have seven additional fields in the database, one for each color. Each field holds a 1 or 0 (true/false) value, and I SELECT based on whatever the user has checked off. (I didn't like this solution so much, because it seemed kind of wasteful to add seven additional fields...especially since most pictures in this table will only have 3-4 colors max, though some could have up to 7. So that means I'm storing a lot of zeros.) Also, if I added more searchable colors later on (which I don't think I will, but it's always possible), I'd have to add more fields.
(Option 2)
-For each image row, I could have a "colors" text field that stores space-separated color names (or numbers for the sake of compactness). Then I could do a fulltext match against search through the fields, selecting rows that contain "red yellow green" (or "1 3 4"). But I kind of didn't want to do fulltext searching because I already allow a keyword search, and I didn't really want to do two fulltext searches per image search. Plus, if the database gets big, fulltext stuff might slow down.
Any better options that I didn't think of?
Thanks!
Side Note: I'm using PHP to work with a MySQL database.
© Stack Overflow or respective owner