I have a relational database (innoDB) which is a tagging system with different 'tag types'. I need to retrieve records that contain ALL tags from multiple columns but I'm having some trouble getting the result I'm after.
There is a main 'targets' table, and 2 'tags' tables. Each 'tags' table represents different 'tagtypes'.
my_targets
=====================================================
id name url tagtype1_id tagtype2_id
-----------------------------------------------------
1 file1 url1 1 5
2 file2 url2 4 5
3 file2 url2 2 5
4 file2 url2 2 2
5 file3 url3 4 3
my_tagtype1 my_tagtype2
================= ================
id title id title
----------------- ----------------
1 sdrty 1 sdfg
2 fssdf 2 wpoie
3 qweok 3 q;jej
4 awerk 4 slth
5 w;eir 5 aw;eoi
The query:
SELECT * FROM
(SELECT t.target_name, t.target_url
FROM my_targets t
INNER JOIN my_tagtype1 ON t.tagtype1_id = my_tagtype1.tagtype1_id
WHERE my_tagtype1.tagtype1_id IN (2,4)
GROUP BY target_name
HAVING COUNT(distinct my_tagtype1.tagtype1_id) = 2) AS t1
INNER JOIN
(SELECT t.target_name, t.target_url
FROM my_targets t
INNER JOIN my_tagtype2 ON t.tagtype2_id = my_tagtype2.tagtype2_id
WHERE my_tagtype2.tagtype2_id IN (5)
GROUP BY target_name) AS t2
The problem
If a user selects the following tags:
tagtype1 tagtype2
========== ==========
id id
---------- ----------
2 5
4
..the result is:
target_name target_url target_name target_url
=============================================================
file2 url2 file2 url2
file2 url2 file1 url1
And this is what it should be:
target_name target_url
===============================
file2 url2
Any suggestions are greatly appreciated. Thanks