Reputation: 455
I have these tables:
Users, A table contains the users:
+--------------------------
| ID | Name |
+--------------------------
Dogs, A table contains the dogs (Last change is a time stamp telling when this dog status last changed):
+---------------------------------------------------------
| ID | Name | Last_Changed_At |
+---------------------------------------------------------
Users_Dogs_Relations, A table that describe which dog belong to which user, where multiple dogs can be belong to one user, multiple users can have the same dog, and multiple dogs can be belong to multiple users. (In short, any user can be related to any dog):
+------------------------------------
| UserID | DogID |
+------------------------------------
Users_Friend_Relation, A table describe which user is friend of which user:
+------------------------------------
| UserID1 | UserID2 |
+------------------------------------
What i want to do is to tell Steve (one of the users), all the name of the dogs that his friends have (ordered by Last_Changed_At from a given timestamp).
for example, Steve with given time 11:23:00, will query all the dogs of Steve's friends ordered by the timestamp and only below 11:23:00. Oh, And i dont want that dogs will appear twice. Any one can give me some clue?
Upvotes: 0
Views: 41
Reputation: 125620
You have to join all your tables on correct columns
Users
to Users_Friend_Relation
to get friends of SteveUsers_Dogs_Relations
to Users_Friend_Relation
to get dogs of *Steve*s friendsDogs
to Users_Dogs_Relations
to get these dogs namesand specify your where
conditions.
SELECT DISTINCT d.Name
FROM Users u1
JOIN Users_Friend_Relation f ON u1.ID = f.User1ID
JOIN Users_Dogs_Relations udr ON udr.UserID = f.User2ID
JOIN Dogs d ON udr.DogID = d.ID
WHERE u1.Name = Steve
AND d.Last_Changed_At < '11:23:00'
Upvotes: 1