Jump to content

1:n Join Question


kc9ddi

Recommended Posts

I'm developing a simple photo album project.  I have one table that stores information about each photo (filename, format, size, etc.) and then a table of keywords.  The keywords table looks like:

[code]
id INT primary key,
keyword VARCHAR,
photo_id INT
[/code]

Each keyword gets its own row in the table, even if multiple photos have the same keyword.  Also, each photo can have multiple keywords that point to the same photo_id.  I think this is a pretty standard setup.

What I'm trying to do is something like SELECT * FROM photos WHERE keyword='keyword1' AND keyword='keyword2' -- that is, find all photos that have BOTH keyword1 and keyword2.  I figured out a JOIN statement that does this for keyword1 OR keyword2, but am having trouble working one that does AND.

Any ideas?
Link to comment
Share on other sites

[code]
SELECT p.*
FROM photos AS p
JOIN keywords AS k1 ON p.photo_id = k1.photo_id
JOIN keywords AS k2 ON p.photo_id = k2.photo_id
WHERE k1.keyword LIKE 'keyword1' AND k2.keyword LIKE 'keyword2'
[/code]

or if you wanted to  do it weighted where it could match either one or both of the keywords

[code]
SELECT p.*,
CASE WHEN k1.id IS NOT NULL AND k2.id IS NOT NULL THEN 2
    WHEN k1.id OR k2.id IS NOT NULL THEN 1
    ELSE 0 END AS search_score
FROM photos AS p
LEFT JOIN keywords AS k1 ON p.photo_id = k1.photo_id AND  k1.keyword LIKE 'keyword1'
LEFT JOIN keywords AS k2 ON p.photo_id = k2.photo_id AND k2.keyword LIKE 'keyword2'
GROUP BY p.photo_id HAVING search_score > 0 ORDER BY search_score DESC
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.