randomKek
randomKek

Reputation: 1128

mysql left join exists

Tables:

I need a query to search for friends (name), and check if they exists in the users table, so then they are also on the website registered.

Is this possible with a left join, and if so how?

Thanks.

Upvotes: 0

Views: 3076

Answers (2)

Joe Stefanelli
Joe Stefanelli

Reputation: 135888

SELECT ff.id, ff.uid, ff.friendUid, ff.name, u.id, u.name
    FROM usersFacebookFriends ff
        LEFT JOIN users u
            ON ff.name = u.name;

If you want only those that exist:

SELECT ff.id, ff.uid, ff.friendUid, ff.name, u.id, u.name
    FROM usersFacebookFriends ff
        INNER JOIN users u
            ON ff.name = u.name;

If you want only those that don't exist:

SELECT ff.id, ff.uid, ff.friendUid, ff.name, u.id, u.name
    FROM usersFacebookFriends ff
        LEFT JOIN users u
            ON ff.name = u.name
    WHERE u.id IS NULL;

Upvotes: 3

dfsq
dfsq

Reputation: 193311

I guess this should make a job. If facebook friend is not registered with your site corrsponding joined User table fields will be NULL.

SELECT f.name, u.* FROM usersFacebookFriends AS f
LEFT JOIN users AS u
ON f.friendUid = u.id
WHERE f.uid = 123

Change LEFT JOIN to INNER JOIN if you need to find only those who exist.

Upvotes: 0

Related Questions