PHP MySQL内部连接多个值

时间:2014-10-09 08:02:51

标签: php mysql inner-join

我得到了这张桌子:

用户

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

nachrichten

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

我使用此代码从user1获取昵称和profilpic:

$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/>';
}

但是我如何从user2获得昵称和profilpic?

2 个答案:

答案 0 :(得分:0)

您可以为第二个用户添加另一个包含用户表的联接

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

答案 1 :(得分:0)

试试这个:

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%'