Tom Hardy
Tom Hardy

Reputation: 25

MYSQL Inner Joins with OR condition

I have 3 tables with the following columns:

Table1:

userId | seriesId | content

Table2:

followerId | followeeId

Table3:

followerId | seriesId

What I'm trying to do is something like this:

SELECT Table1.content 
FROM Table1 
    (INNER JOIN Table2 ON Table2.followeeId=Table1.userId WHERE Table2.followerId=X) 
OR (INNER JOIN Table3 ON Table3.seriesId=Table1.seriesId WHERE Table3.followerId=X)

'X' will be some dynamically generated number. I'm not sure if this is even the right approach but you get what I'm trying to do right? My question is, what is the right way to implement something like this? Please let me know in the comments if any part of my question is not clear.

Upvotes: 2

Views: 67

Answers (2)

user3327034
user3327034

Reputation: 405

You can do this too..

SELECT Table1.content 
FROM Table1 
LEFT JOIN Table2 ON Table2.followeeId=Table1.userId 
LEFT JOIN Table3 ON Table3.seriesId=Table1.seriesId
where Table2.followerId=X or Table3.followerId=X;

The other way is Union

select table1.content
from table1
INNER JOIN Table2 ON Table2.followeeId=Table1.userId 
where followerId = X
union
select table1.content
from table1
INNER JOIN Table3 ON Table3.seriesId = Table1.seriesId
where Table3.followerId = X;

Upvotes: 2

Barmar
Barmar

Reputation: 782683

Use a UNION:

SELECT Table1.content
FROM Table1
INNER JOIN Table2 ON Table2.followeeId=Table1.userId 
WHERE Table2.followerId=X
UNION
SELECT Table1.content
INNER JOIN Table3 ON Table3.seriesId=Table1.seriesId 
WHERE Table3.followerId=X

Upvotes: 2

Related Questions