I'm trying to query three tables and find results where the primary table matches ALL the criteria rows in the second table, and ANY of the criteria rows in the third table.
The tables (simplified):
// table entries
entryId
1
2
// table entriesEthics
entryId ethicsId
1 1
1 2
2 1
//table entriesCategories
entryId categoryId
1 1
1 2
2 1
2 2
I'm trying to find all entries that have ethicsId 1 AND ethicsId2, and have categoryId 1 OR categoryId 2 (or both).
My query:
SELECT entries.*, entriesEthics.ethicsId AS entryEthicsId
FROM entries JOIN entriesEthics ON entries.entryId=entriesEthics.entryId
JOIN entriesCategories ON entries.entryId=entriesCategories.entryId
WHERE (entriesEthics.ethicsId=1 OR entriesEthics.ethicsId=2) AND
(entriesCategories.categoryId=1 OR entriesCategories.categoryId=2)
GROUP BY entryId, entryEthicsId
HAVING count(entryEthicsId) =2
The result:
Array
(
[0] => Array
(
[entryId] => 1
[hidden] => 0
[entryEthicsId] => 1
)
[1] => Array
(
[entryId] => 1
[hidden] => 0
[entryEthicsId] => 2
)
)
As you can see, I'm getting two copies of entry 1, which I'm pretty sure is because I'm creating the field entryEthicsId (which I need in order to limit my result to only those entries that have BOTH ethicsIds).
I tried using DISTINCT but again, since the rows are different (thanks again to my adding entryEthicsId) it was no help.
I'd love to avoid having to post-process the results to get rid of the duplicates, but I'm having trouble figuring out how.
Anyone who lives, breathes and/or dreams SQL queries have a tip for me?