How do I select single entry based on mutiple values?
Okay – here’s one for the guys smarter than me – IE: everyone. An interesting query.
(CF8, MySQL5)
I’m building an internal stock library for a large firm. Easy job – and its always the easy ones that knock you, ain’t it?
Basically, its very very simple, I have three tables.
Table 1 is a list of images (ImageTbl) – this has a lot of data on it, but the only important thing from ImageTbl is the unique identifier, RowID. It looks something like this
| Rowid | Photo |
|---|---|
| 1 | Gold.jpg |
| 2 | iron.jpg |
| 3 | train.jpg |
| 4 | foo.jpg |
| 5 | bar.jpg |
…Etc. for hundreds of images.
Table 2 is a list of features (FeatureTbl) that can be applied to any image, its literally just a RowID and a Feature, IE
| Rowid | Feature |
|---|---|
| 1 | Mining |
| 2 | Coal |
| 3 | Rail Transport |
| 4 | Iron Ore |
| 5 | Road Transport |
| 6 | Refined Product |
| 7 | Gold Ore |
etc. for about 50-odd features. Every image that is uploaded to the system is then given AT LEAST one of these categories, but it can be as many as 9 or 10.
This is where the fun starts…. So, maybe I’ve been given the wrong advice, but I’ve been told not to store strings, but to “normalise” the database, which means I’ve got a third table which has an image number and a feature number: (ImageFeaturesTbl)
ImageNo FeatureNo 1 1 1 3 1 5 2 1 2 7 3 5 etc 100's of records
(This is how I was told to do this, I can probably change the system if I really need to)
Now they want to have a “search” function. Gimme all images that feature “coal”. Got the features list as a checklist on a form, check the feature you want, hit submit – voila! Easy – run a query on ImageFeaturesTbl and Bob is your auntie.
Select imageNo from ImageFeaturesTbl where feature=#FORM.FeatureNo#
Works a treat! Sits out all the images that has the "Coal" featreNo. But now, what if there are more than 2 categories? What if they want all images that has “Coal” or “gold” on it – that one I also figured out, the “OR” query. I can do a loop and search for images on ImageFeaturesTbl that has either one or the other. So this is not the problem either.
The fun really starts with the “and” query – select images that has both “coal” and “rail transport”… and this is where I get stuck. I’ve literally worked till 4:00 AM this morning – and it’s a weekend; and up again at 7 trying to solve this puzzle. I’m miserable!
Basically I’m wanting to get from ImageFeaturesTbl a list of image numbers that contains ALL the selected features. It could be one feature (always at least one) but it could be Nine or 10. But it has to have ALL the featurees. So the system has to give me all the images that shows coal being transported on rail in summer at the harbour, for instance.
The database and tables exist, but how the hell do I write that select query….
Thanks - I'll email the winning answer a crate of beer.
