randomKek
randomKek

Reputation: 1128

php mysql query join merge

I want to know if these two queries can be merged, I will explain a little what the queries do.

This is my table structure:

So we got users, users have friends, users can create activities and multiple users can be bound to activities. I hope that is clear.

SELECT DISTINCT
    A.description, A.date, A.time
FROM
    usersFacebookFriends UF
JOIN
    activitiesUsers AF
ON
    AF.uid = UF.friendUid
JOIN
    activities A
ON
    A.id = AF.activityId
WHERE
    UF.uid = :uid

The uid parameter in the query is obviously the user id. After the execution of that query I currently do this:

foreach($activities as $activity){
    // SELECT 
    //     U.id, U.name, U.firstName, U.level
    // FROM
    //     activitiesUsers AF
    // JOIN
    //     users U
    // ON
    //     U.id = AF.uid
    // WHERE
    //     AF.activityId = ?
}

So its kinda double, I still loop through all the activities after they are fetched in the first query, and then I get all the users, is it possible to merge these queries so I don't have to loop after obtaining all the activities and if so how?

Thanks for help

Upvotes: 0

Views: 104

Answers (1)

dgw
dgw

Reputation: 13646

SELECT
  A.description, A.date, A.time,U.id, U.name, U.firstName, U.level
FROM
  usersFacebookFriends UF, activitiesUsers AF, activities A, users U
WHERE
  UF.uid = :uid AND UF.friendUid=AF.uid AND AF.activityId=A.id AND AF.uid=U.id ;

This should do the trick.

Upvotes: 2

Related Questions