What is the correct way to join two tables in SQL?

I have two tables. The first table contains simple user data and has columns

$username, $text, $image 

(this is called "USERDATA").

The second table contains information about which users "follow" other users who are configured with columns

$username and $usertheyfollow 

(this is called "FOLLOWS").

What I need to do is display the data separately for each user so that they are important to them. This means that userABC, for example, should be able to view the entries $textand $imagefor all users, he / she should be. For this, I believe that I need to write a sql query that includes the first check of who the registered user is (in this case userABC), then select all the instances $usertheyfollowin the FOLLOWS table, which has the corresponding value. "userABC."Then I need to return to my table USERDATAand select $textand $image, which is relevant $usertheyfollow. Then I can just display it with the echo command or the like ...

SQL-? ?

+3
3

, . @jam6459 .

:

SELECT userdata.text, userdata.image, follows.userFollow
  FROM userdata
  LEFT JOIN follows ON follows.userFollow = userdata.username
  WHERE follows.userId = $username

, Id, jam. , "USERDATA". .

+1

:

userdata

 ______________________________
| id | username | text | image |
|------------------------------|
| 1  | jam      | text | image |
+------------------------------+
| 2  | sarah    | text | image |
+------------------------------+
| 3  | tom      | text | image |
+------------------------------+

follows

 _____________________
| userId | userFollow |
|---------------------|
|   1    |     2      |
+---------------------+
|   1    |     3      |
+---------------------+

SQL:

SELECT userdata.text, userdata.image FROM follows LEFT JOIN userdata ON follows.userFollow = userdata.id WHERE follows.userId = 1

, "1"

+2
function get_text_image($username)
{
     $sql = "SELECT * FROM USERDATA where username='".$username."'";  
     $result = mysql_query($sql);

     while($row = mysql_fetch_array($result))
     {
         echo $row['text'];
         echo $row['image'];
     }
}



function display_data_of_followers($userid)
{
     $sql = "SELECT usertheyfollow FROM follow WHERE userid = ".$userid."";
     $result = mysql_query($sql);

     while($row = mysql_fetch_array($result))
     {
          get_text_image($row['usertheyfollow']);
     }
}

display_data_of_followers($userid);
-1
source

All Articles