连接两个MySQL表并在表中显示结果

时间:2019-02-02 18:02:53

标签: php mysql

我有两个表,分别称为t_user和t_chat。我试图在如下所示的PHP表中显示来自t_chat的消息。

     $quotes_qry="SELECT * FROM t_chat ORDER BY id DESC LIMIT $start, $limit";
     $result=mysqli_query($mysqli,$quotes_qry);
    <?php   
                            $i=0;
                            while($row=mysqli_fetch_array($result))
                            {   

                        ?>
                            <tr>

                              <td><?php echo ++$sr+$start;?></td> 
                              <td><?php echo $row['sender'];?></td>                
                              <td><?php echo nl2br($row['receiver']);?></td>
                              <td><?php echo nl2br($row['message']);?></td>
                              <td><?php echo time_elapsed_string($row['time']);?></td>
                              <td><a href="?id=<?php echo $row['id'];?>" class="" onclick="return confirm('Are you sure you want to delete this row?');"><img src="images/delete-icon.png"></a></td>
                            </tr>
                    <?php
$i++;
                        }
                ?> 

我要显示位于名为t_user with username column的表中的发送方和接收方名称。我是PHP新手,对如何实现它感到困惑。让我知道是否有人可以帮助我完成任务。非常感谢!

注意:t_chat表具有名为发件人和接收者的用户ID列名,当前我在上表中显示该用户ID,而我想显示用户名。 谢谢

2 个答案:

答案 0 :(得分:1)

联接可能看起来像这样:

SELECT t_chat.sender AS 'sender', t_chat.receiver AS 'receiver', t_chat.message AS 'message', t_chat.time AS 'time', t_chat.id AS 'id', user1.username AS 'senderusername', user2.username AS 'receiverusername'  
FROM t_chat 
LEFT JOIN t_user AS user1 ON t_chat.sender = user1.id
LEFT JOIN t_user AS user2 ON t_chat.receiver = user2.id
ORDER BY id DESC

在此示例中,我两次连接表(分别作为user1和user2),以便t_user表针对每次查找独立引用。

我还使用AS为每列命名,以使它们在以后的代码中更易于引用。

答案 1 :(得分:0)

尝试以下SQL(t_user表必须具有与t_chat中的id相匹配的userid列):

$quotes_qry="SELECT t1.sender, t1.receiver, t1.message, t1.time, t2.username FROM t_chat AS t1 INNER JOIN t_user AS t2 ON t1.userid=t2.id ORDER BY t1.id DESC LIMIT $start, $limit";

您可以在本教程中找到有关MySQL JOIN的更多详细信息和示例,

https://coursesweb.net/php-mysql/mysql-inner-left-join-right-join_t