简体   繁体   中英

PHP MySQL inner join multiple values

I got this tables:

Table user :

|    userid    | nickname   |   profilpic  |
|33460794335580| KING_ED    |5435345345.jpg|
|86426315360152| Caro010716 |654664656.jpg | 

Table nachrichten :

|              file             |      user1      |     user2     |
|33460794335580_86426315360152  | 33460794335580  |86426315360152 |

I use this code to get nickname and profilpic from user1:

$myid = 33460794335580;
$msgquery = mysqli_query($con, "SELECT
            user.nickname,user.profilpic,nachrichten.user1,nachrichten.user2
            FROM user
            INNER JOIN nachrichten ON nachrichten.user1 = user.userid
            WHERE nachrichten.file LIKE '%$myid%'");


while($daten = mysqli_fetch_assoc($msgquery))
{
    echo 'The user-id ' . $daten['user1'] . ' got the Nickname: ' . $daten['nickname'] . ' and profilpic is: ' . $daten['profilpic'] . '<br/>';
    echo 'The user-id ' . $daten['user2'] . ' got the Nickname: ' . ???????????????? . ' and profilpic is: ' . ?????????????? . '<br/>';
}

But how can I get also the nickname and profilpic from user2?

You can add another join with user table for second user

SELECT 
  u.nickname nickname1,
  u.profilpic profilpic1,
  u1.nickname nickname2,
  u1.profilpic profilpic2,
  n.user1,
  n.user2 
FROM
  nachrichten n
  INNER JOIN  user u 
    ON n.user1 = u.userid 
  INNER JOIN  user u1 
    ON n.user2 = u1.userid 
 WHERE ....

Demo

Try this:

SELECT u1.nickname AS user1_name,u1.profilpic AS user1_pic, u2.nickname AS user2_name, u2.profilpic AS user2_pic 
FROM nachrichten n
INNER JOIN user u1 ON n.user1 = u1.userid
INNER JOIN user u2 ON n.user2 = u2.userid
WHERE nachrichten.file LIKE '%$myid%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM