How to get all rows from a table 1 using the specific matching row from table 1 and table 2

Viewed 78

I m trying to get all rows from table 1 using the specific matching row from table 1 and table 2 and then sort them as per date from table 1

Here's an example.

Posts (table 1)

u_id title date
1 some 19-07-2021
2 some 18-07-2021

Follows (table 2)

u_id r_u_id
1 2

Now, let my user_id = 2.

I m trying to get all the columns in posts (table 1) WHERE its u_id matches with u_id of follows (table 2) where its r_u_id is user_id I defined, along with all the columns in posts (Table 1) where u_id is user_id I defined ordered by date from posts (table 1)

Here's the code I have tried so far:

SELECT * 
FROM 
  posts 
  LEFT JOIN follows ON posts.u_id = follows.u_id 
WHERE 
  follows.r_u_id = '$user_id' 
  AND posts.category = '$u_category' 
  AND posts.language = '$u_language' 
  AND posts.status = 'Live' 
ORDER BY posts.date";

The above query works perfectly fine by returning all the columns in the posts (Table 1) where the u_id matches with u_id of follows (table 2) where its r_u_id is user_id I defined.

But it doesn't return the columns where u_id is user_id I defined, so I added this posts.u_id = '$u_id' as below.

SELECT * 
FROM 
  posts 
  LEFT JOIN follows ON posts.u_id = follows.u_id 
WHERE 
  follows.r_u_id = '$user_id' 
  AND posts.u_id = '$user_id' 
  AND posts.category = '$u_category' 
  AND posts.language = '$u_language' 
  AND posts.status = 'Live' 
ORDER BY posts.date";

And now it returns nothing.

I don't understand, as I already have a where clause mentioned returning the specific language and specific category from posts table, but why it doesn't work if I add another clause with u_id is my user_id.

The desired output I should be getting from the query I need should be Every column in posts (Table 1) listed above.

Cause, The LEFT JOIN of follows ON posts.u_id = follows.u_id will get me the columns from the posts (Table 1) that matches the u_id of posts (Table 1) with u_id of follows (Table 2) with the condition of r_u_id of my user_id, so it will get the column #1 from posts (Table 1), However, as I also mentioned the where clause as posts.u_id = '$u_id', it will also get column #2 from posts (Table 1) as well.

so the desired output will look like the below table.

Desired output :

u_id title date
2 some 18-07-2021
1 some 19-07-2021
0 Answers
Related