- Testing FQL Queries
- Finding the User's Friends
- Finding the User's Links
- Executing the FQL Queries
- Putting It All Together
- Summary
Finding the User's Friends
In our sample application, we'll display the names of a few friends of the current user, as well as the last five links that the user has published.
To get the friends of the current user, we have to query the friend table, which contains pairs of user IDs. We'll supply the first UID and use the second UID (the friends) in subsequent queries. The current user ID will be known in our Facebook Connect application, but we also have to supply one in the Facebook API Test Console application. Fortunately, Facebook provides a convenient value (your own user ID) in the left toolbar, so it's easy to copy it into the FQL queries.
To select the list of friends' user IDs, use this FQL query:
SELECT uid2 FROM friend where uid1 = current-user-ID
You could store the returned value and perform numerous FQL queries to return individual friends' details, but it's much more effective to use the following query in the IN condition of the subsequent query:
SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend where uid1 = current-user-ID)
To display just a few friends, use the LIMIT clause in the inner SELECT clause:
SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend where uid1 = current-user-ID LIMIT number-of-rows)
This query will return the same list of friends every time it's executed. To randomize the list, use the rand function to sort the inner query:
SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend where uid1 = current-user-ID ORDER BY rand() LIMIT number-of-rows)
Finally, you might want to take the random selection of friends that we've just generated, and sort that list by name. No problem[md]just append the ORDER BY name clause at the end of the (already convoluted) query:
SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend where uid1 = current-user-ID ORDER BY rand() LIMIT number-of-rows) ORDER BY name