I have a table similar to the following:
REL_Aid_To_AttributeValue:
ID AttributeValueID
101 1319
101 1320
101 1344
101 1345
102 1319
102 1320
102 1321
102 1336
103 1320
103 1336
I have another table that groups these AttributeValueIDs by type:
TBL_AttributeValues:
AttributeValueID AttributeTypeID
1319 1
1320 1
1321 1
1336 2
1344 3
1345 3
I have a third table that gives information about each ID from the first table:
TBL_Aids:
ID Title Author etc.
101 Aid About Spiders John Doe
102 Aid About Mites Jane Doe
103 Aid About Beetles Joe Schmo
I would like to return results of IDs (and information about them, like the Title, Author, etc.) that contain ONLY AttributeValueIDs 1319 OR (inclusive) 1320, within AttributeTypeID=1. So I would hope to return 101 because it only has 1319 and 1320 for AttributeType 1, and also 103 because it has only 1320 for AttributeType 1. I would not want to return 102 because although it has 1319 and 1320, it also has 1321, which is of AttributeType 1 as well.
I tried the following:
SELECT a.ID, a.Title, c.AttributeTypeID,
COUNT(b.AttributeValueID)AS Total
FROM TBL_Aids as a,
REL_Aid_To_AttributeValue as b,
TBL_AttributeValues as c
WHERE a.ID=b.AidID
AND b.AttributeValueID=c.ID
AND a.Status=2
AND AttributeTypeID=1
AND (b.AttributeValueID=1319
OR b.AttributeValueID=1320)
GROUP BY a.ID, a.Title,
c.AttributeTypeID
HAVING COUNT(b.AttributeValueID) <= 2
But it still returns 102 as a result, because it has already limited by 1319 and 1320 and is counting that total instead of the overall total of AttributeValueIDs for Type 1. Do I need some sort of subquery to accomplish this? Any help would be appreciated! Thank you so much.
1 Answer