I come across my MySQL query skill limits, so I hope some SQL guru can help with this. The situation is as follows:
I have images that can be tagged. As you might expect, this will be stored in three tables:
- Picture
- Tag
- Tag_map (matches images with tags)
I have an SQL query that computes related tags based on a tag id. The query basically checks which other tags were used for images for images using this tag. Example:
Image1 is labeled “Bear”
Image2 is labeled “Bear” and “Canada”
If I drop “Bear” (or its tag identifier) into the request, it will return “Canada”. It works great. Here's the request:
SELECT tag.name, tag.id, COUNT(tag_map.id) as cnt
FROM tag_map,tag
WHERE tag_map.tag_id = tag.id AND tag.id != '185' AND tag_map.image_id IN
(SELECT tag_map.image_id FROM tag_map INNER JOIN tag ON tag_map.tag_id = tag.id WHERE tag.id = '185')
GROUP BY tag_map.id LIMIT 0,100
The part I'm stuck for is the bill. For each linked tag returned, I want to know how many images are in this tag. Currently, it always returns 1, even if there is, for example, 3. I tried to count different columns, all leading to the same conclusion, so I think there is a flaw in my thinking.
source
share