Kevin Jensen Petersen
Kevin Jensen Petersen

Reputation: 513

SQL Query with OR-Clause

I have two tables which I'm trying to combine and get data from one of them, depending on the query.

My sql query: (Which does not work)

SELECT *
FROM contacts
    INNER JOIN users
    (ON contacts.user_id_sender = users.id
    WHERE contacts.user_id_sender = '$user_id' AND contacts.status = 1)
        OR
    (ON contacts.user_id_receiver = users.id
    WHERE contacts.user_id_receiver = '$user_id' AND contacts.status = 1)

Basically, I have a class that needs to return the 'users' of which 'contacts' that is a part of the users id, and has a status of 1.

The idea behind this is a Contact/Friend system table. I basically have a Users and Contacts table, and I need to return the Users data depending on which of the contacts has relation to OUR user id.

Upvotes: 0

Views: 44

Answers (1)

Norbert
Norbert

Reputation: 6084

The () brackets in the ON where placed incorrect + there was a WHERE statement in the ON clause, which is not allowed. This looks like what you wrote, but then syntactically works:

SELECT *
FROM contacts
INNER JOIN users
ON (contacts.user_id_sender = users.id 
     AND contacts.user_id_sender = '$user_id' 
     AND contacts.status = 1)
    OR
(contacts.user_id_receiver = users.id
AND contacts.user_id_receiver = '$user_id' AND contacts.status = 1)

Upvotes: 2

Related Questions