The query below isn't returning what I want it to.
I want to get a list of a friend's favourite charities, but with an extra field denoting what
my relationship with each charity is.
In terms of defining "my" and "friend": I've got a table that manages relationships between users:
UserContacts. It's got one field called userID and another called contactID; both link to the main Users table (it's also got an autoincrement PK field). In this sense, "I" am the userID, and my "friend" is the contactID.
I've got, in a similar fashion, a table that manages relationships between users and charities:
UserCharities. It's got one field called userID and another called charityID. It's got another integer field that stores the type of relationship - in this case I'm only interested in types 1 and 3.
So, first effort: for a given UserContact ID, get a list of the friend's charities. The "friend" is denoted by the contactID in the UserContacts table, so it's fairly straightfoward:
Code:
SELECT c.charityID, c.charityName
FROM UserContacts uc
INNER JOIN UserCharities friendCharity ON friendCharity.userID = uc.contactID
INNER JOIN Charities c ON c.charityID= friendCharity.charityID
WHERE uc.UserContactsID = 1234
AND friendCharity.relationshipType IN (1,3)
ORDER BY c.charityName
This works fine.
However, when I try to add the second bit - find out the relationship between
me and the charities listed (ie: the UserID of the UserContacts instead of the ContactID), I start getting a lot more rows than I expected. This is how I amended it:
Code:
SELECT c.charityID, c.charityName, myCharity.relationshipType
FROM UserContacts uc
INNER JOIN UserCharities friendCharity ON friendCharity.userID = uc.contactID
INNER JOIN UserCharities myCharity ON myCharity.userID = uc.userID
INNER JOIN Charities c ON c.charityID= friendCharity.charityID
WHERE uc.UserContactsID = 1234
AND friendCharity.relationshipType IN (1,3)
ORDER BY c.charityName
If I drop a "GROUP BY c.charityID" into it, it doesn't seem to pull out the right data for my relationship with the charity.
As you can probably see, I'm a bit lost. I don't know how I've managed to get it wrong, or what to do to get it right. Any help would be greatly appreciated.