gpt4 book ai didi

php - Mysql 查询获取共同好友计数并将其显示在 php 的表中

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:06 25 4
gpt4 key购买 nike

我有一个名为 myfriends 的表,其中包含 2 列:

  • friend_id1
  • friend_id2

当某人是某些人的 friend 时,会有两条记录。例如,我们有 4 个成员:1000、1001、1002 和 1003。

如果 1000 和 1001 互为好友,则会有两条记录:(1000, 1001)(1001, 1000)。为了示例,我们假设 1000 和 1002 也是 friend 。

我显示与登录用户不是 friend 的人(例如,1000),我想在每个人旁边显示共同 friend 数。考虑到这个例子,我需要在 1002 前面显示 1,在 1003 前面显示 0。

这是我用来列出所有成员的代码和查询的一部分,表中名称旁边有添加为好友按钮。

$query ="SELECT profile_name,friend_id from friends
WHERE friend_id<>'$friendID'
AND
friend_id NOT IN( SELECT friend_id2 from myfriends WHERE friend_id1='$friendID')";

$results = @mysqli_query($conn, $query) or die
$row = mysqli_fetch_row($results);

echo "<table width='50%' border='1'>";
while ($row) {
echo "<tr><td>{$row[0]}</td>";
?>
<td><button onclick = "window.location.href='friendadd.php?addfriend=<?php echo $row[1];?>'">Add as friend</button></td></tr>
<?php
$row = mysqli_fetch_row($results);
}
echo "</table>";

我想在个人资料名称和添加为好友按钮之间显示每个人的共同好友数。

最佳答案

试试这个:

SELECT
f.profile_name,
f.friend_id,
COUNT(DISTINCT m2.friend_id1) AS count_mutual
FROM
friends AS f
LEFT JOIN myfriends AS m1
ON (m1.friend_id1 = f.friend_id)
LEFT JOIN myfriends AS m2
ON (m1.friend_id2 = m2.friend_id1 AND m2.friend_id2 = '$friendID')
WHERE
f.friend_id <> '$friendID'
AND f.friend_id NOT IN(SELECT
friend_id2
FROM
myfriends
WHERE
friend_id1= '$friendID')
GROUP BY
f.friend_id

您可以看到它正在处理 http://sqlfiddle.com/#!2/fc893/2/0 .为了计算共同 friend 的数量,您需要两次加入 myfriends 表,第一次是获取您选择的人的所有 friend 列表,第二次是检查这些人中谁是 $friendID 人的 friend 。

关于php - Mysql 查询获取共同好友计数并将其显示在 php 的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com