【发布时间】:2012-07-06 00:12:39
【问题描述】:
我正在构建一个用户可以关注其他用户并被关注的应用。
用户还可以查看其他用户正在关注谁。
现在假设 user1 正在查看 user2 关注的人,我需要找到 user2 关注的所有人员 ID,并将其与 user1 关注的人进行比较。
而不是只返回与 user1 和 user2 匹配的所有用户的 ID(我在其他论坛中看到过),我还需要检索所有 user2 的以下 ID 和用户名作为一个标志,指示被关注的人是否也被 user1 关注。
我已经让它在 PHP 中工作,每个查询都有一个双 for 循环,但我担心这段代码会很昂贵,并且使用单个 MYSQL 查询会更好地优化。
相关表和列:
following_table
follower_id
followed_id
following: varchar -- 'true' or 'false'
user_table
user_id
user_name
这是我的 PHP 代码:
$user_id1 = '1991';
$myFollowingQuery = "SELECT following_table.followed_id, user_table.user_name
FROM following_table
INNER JOIN user_table ON
following_table.followed_id = user_table.user_id
WHERE following_table.following = 'true'
AND following_table.follower_id = '$user_id1'";
$user_id2 = '1985';
$userFollowingQuery = "SELECT following_table.followed_id, user_table.user_name
FROM following_table
INNER JOIN user_table ON
following_table.followed_id = user_table.user_id
WHERE following_table.following = 'true'
AND following_table.follower_id = '$user_id2'";
$userFollowingResult = mysql_query($userFollowingQuery)
or doResponse('error',"Couldn't connect to the database");
$myFollowingResult = mysql_query($myFollowingQuery)
or doResponse('error',"Couldn't connect to the database");
for($i = 0; $i< mysql_num_rows($userFollowingResult);$i++){
$loopArray = array(followed_id => mysql_result($userFollowingResult,$i,"followed_id"),
followed_name => mysql_result($userFollowingResult,$i,"user_name"));
for($j = 0; $j< mysql_num_rows($myFollowingResult);$j++){
if(mysql_result($userFollowingResult,$i,"followed_id")
==mysql_result($myFollowingResult,$j,"followed_id")) {
$loopArray['is_following'] = 'true';
break;
}
if($j==mysql_num_rows($myFollowingResult)-1){
$loopArray['is_following'] = 'false';
break;
}
}
$resultArray[$i] = $loopArray;
}
echo json_encode($resultArray);
【问题讨论】:
-
我不明白你的意思,是不是像你想要的相互关注列表?
-
能否请您也粘贴表格结构(
show create table TABLE_NAME)。据我猜测,您可以使用 MINUS, INTERSECT 来解决您的问题。 -
很抱歉成为新手。从未使用过(显示创建表 TABLE_NAME)。试图让它与 Querious 一起工作,但没有得到任何结果。基本上 following_table 包括:follower_id | follow_id |日期创建 |以下(true 或 false。) user_table 包括: user_id |用户名 |追随者 |关注 |等等等等。
标签: mysql