SQL Inner Join 3 Tables

So, I believe that I need Inner Join for this request, but I'm not 100% sure.

First of all, see the database diagram:

Click here for database diagram.

What I'm trying to achieve:

  • I am trying to get all the messages (so user_username, text, published_at FROM Messages), where the username is the same as follow_username, and where follow_username has the name follower_username = ?.
  • In fact, did everyone accompany ?, I want to receive all their messages.

Where? = username entered

What have i tried so far

I tried several sql statements and still could not succeed. These are the ones I tried.

$sql = "SELECT user_username, text, posted_at FROM Messages, Users, User_Follows WHERE user_username = (SELECT username FROM Users WHERE username = (SELECT followed_username FROM User_Follows WHERE follower_username = ?)) ORDER BY posted_at DESC;";
$sql = "SELECT user_username, text, posted_at FROM Messages, User_Follows WHERE follower_username = ? AND followed_username = user_username;";
$sql = "SELECT user_username, text, posted_at FROM Messages JOIN User_Follows ON user_username = followed_username WHERE follower_username = followed_username;";

Now I think that I need to use the inner join to achieve what I want, but not too sure if this is right or how it is done.

.

+4
2

- :

SELECT M.user_username, M.text, M.posted_at 
FROM Messages M  
INNER JOIN Users U on  M.user_username= u.username
INNER JOIN User_Follows UF  on UF.followed_username = u.username
WHERE UFfollower_username = ? 
ORDER BY posted_at DESC;

, varchar nvarchar , . , , , .

. , , .

- ( , - ), , . , .

, , .

+2

:

select * from messages where user_username in
(
  select followed_username from user_follows
  where follower_username = 'your_input_username'
);
-1

Source: https://habr.com/ru/post/1660823/


All Articles