查询好友表中两个好友姓名的简单方法

发布于 2024-10-31 01:02:15 字数 700 浏览 0 评论 0原文

我有一个朋友表,其中存储了两个朋友的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何处潇湘 2024-11-07 01:02:15

假设表结构为:

Users:
用户 ID 、姓名

好友:
Friendship_id 、 userid_1 、 userid_2

SELECT name 
FROM Friends F JOIN Users U ON (F.userid_2 = U.userid) 
WHERE userid_1 = X

编辑:
如果您想获得这两个名称,可以使用此名称。

SELECT 
  U1.name as name1 , U2.name as name2
FROM 
 Friends F 
 JOIN Users U1 ON (F.userid_1 = U1.userid) 
 JOIN Users U2 ON (F.userid_2 = U2.userid) 
WHERE 
 userid_1 = X

您可以调整 where 子句来查询任一用户 ID。

Assuming the table structure is :

Users:
userid , name

Friends:
friendship_id , userid_1 , userid_2

SELECT name 
FROM Friends F JOIN Users U ON (F.userid_2 = U.userid) 
WHERE userid_1 = X

Edit:
If you want to get both names you can use this.

SELECT 
  U1.name as name1 , U2.name as name2
FROM 
 Friends F 
 JOIN Users U1 ON (F.userid_1 = U1.userid) 
 JOIN Users U2 ON (F.userid_2 = U2.userid) 
WHERE 
 userid_1 = X

You can adjust the where clause to query on either user ids.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文