tags:

views:

102

answers:

2

i've three tables related.

images: id | filename | filesize | ...

nodes: image_id | tag_id

tags: id | name

And i'm using this query to search images containing x tags

SELECT images.* FROM images 
INNER JOIN nodes ON images.id = nodes.image_id 
WHERE tag_id IN (SELECT tags.id FROM tags WHERE tags.tag IN ("tag1","tag2")) 
GROUP BY images.id HAVING COUNT(*)= 2

The problem is that i need to retrieve also all tags contained by the retrieved image, and i need this in the same query.

This the actual query wich search retrieve all tags contained by the image:

SELECT tag FROM nodes 
JOIN tags ON nodes.tag_id = tags.id 
WHERE image_id = images.id and nodes.private = images.private 
ORDER BY tag

How can i mix this two to have only one query?

I need all image table in the results plus the tags of the image. Like: id filename filesize tags

Maybe if is possible concat tags.

+1  A: 

Something like this perhaps?

SELECT i.id, t.name
FROM images i
    INNER JOIN nodes n ON n.image_id = i.id
    INNER JOIN tags t ON t.id = n.tag_id
WHERE i.id IN
(
    SELECT nodes.image_id 
    FROM nodes
        INNER JOIN tags ON tags.id = nodes.tag_id
    WHERE tags.name IN ('tag1', 'tag2')
)
Michael Petito
That returns all tags mixed :/, not for that x image.
BulgedSnowy
You can only get one result set per query statement in SQL. This example gives you a single result set that contains the images and tags as (Image ID, Tag Name) pairs. It's not too difficult to enumerate these pairs and perform the necessary grouping in your client code. If you want separate result sets per image, you'd either have to use a cursor in SQL or a loop in your client code to execute multiple queries (one for each image id).
Michael Petito
A: 

And this ?

SELECT tag FROM nodes 
JOIN tags ON nodes.tag_id = tags.id 
WHERE image_id = images.id 
AND nodes.private = images.private 
AND image_id in (
   SELECT images.id FROM images 
   INNER JOIN nodes ON images.id = nodes.image_id 
   WHERE tag_id IN (SELECT tags.id FROM tags WHERE tags.tag IN ("tag1","tag2")) 
   GROUP BY images.id HAVING COUNT(*)= 2)
ORDER BY tag
Cobusve