I’m not very good with MySQL statements, so I’m looking for some insight. Let’s say a user visits someone else’s page. This will send the username as a parameter to a script to check if the current user and the user’s page they are visiting are friends.
My simple database structure:
FRIENDS TABLE — relationship_id, friend1_ID, friend2_ID, status
ACTIVE_USERS TABLE — id, username, email…etc.
My current SQL statement is as follows:
SELECT *
FROM friends
JOIN active_users ON ( active_users.username = '$username' )
WHERE (
friends.friend_1ID = '$current_user_ID'
AND friends.friend_2ID = active_users.id
AND friends.status = 1
)
While this WORKS, I don’t feel it’s elegant. It returns a row if the two are friends, but this row obviously is a join of the user information row and the relationship row. I would just like to grab the relationship row. Would it be economical to break this up into two statements? For instance, I would query for the visited page’s user ID using the username, and then use that variable in a second statement to grab the relationship. Or is there an easier syntax I have not come across? Help is appreciated!
You can do as follows:
By using an alias named
bfor friends table, we are able to just select fields that belong to that table by using selectb.*, instead of the default*which covers all your joined tables so that’s why it was returning all fields from the tow joined tables.So we just gave alias name to the tables in the query to be able to only select the fields belonging to that alias table.