查询好友表中两个好友姓名的简单方法
我有一个朋友表,其中存储了两个朋友的 ID。当我查询时,假设我的朋友,有没有一种简单的方法可以从用户表中获取我朋友的名字?我使用 PHP 和 MySQL,表没有通过外键连接,但我想我可以连接它们(使用 Navicat)。
我的查询:
session_start();
if(isset($_SESSION['valid_user']))
{
$currentuser= $_SESSION['valid_user'];
}
$friendships= mysql_query("SELECT * FROM friends WHERE Person1 = '$currentuser' OR Person2 = '$currentuser' ");
while($row = mysql_fetch_assoc($friendsips))
{
if ($row['Person1'] == $currentuser) echo $row['Person2']; // quering the users name from here is hard and long thing to do
if ($row['Person2'] == $currentuser) echo $row['Person1'];
}
朋友(friendshipID,Person1,Person2)
用户(ID,姓名,姓氏)
I have friends table where there are stored two friends' IDs. When I query, let's say my friends, is there an easy way to get my friends' names from users table? I use PHP and MySQL and the tables are not connected by foreign key but I think I can connect them (using Navicat).
My query:
session_start();
if(isset($_SESSION['valid_user']))
{
$currentuser= $_SESSION['valid_user'];
}
$friendships= mysql_query("SELECT * FROM friends WHERE Person1 = '$currentuser' OR Person2 = '$currentuser' ");
while($row = mysql_fetch_assoc($friendsips))
{
if ($row['Person1'] == $currentuser) echo $row['Person2']; // quering the users name from here is hard and long thing to do
if ($row['Person2'] == $currentuser) echo $row['Person1'];
}
friends(friendshipID, Person1, Person2)
users(ID, name, surname)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设表结构为:
Users:
用户 ID 、姓名
好友:
Friendship_id 、 userid_1 、 userid_2
编辑:
如果您想获得这两个名称,可以使用此名称。
您可以调整 where 子句来查询任一用户 ID。
Assuming the table structure is :
Users:
userid , name
Friends:
friendship_id , userid_1 , userid_2
Edit:
If you want to get both names you can use this.
You can adjust the where clause to query on either user ids.