编写MYSQL以下用户查询

时间:2012-07-06 00:12:40

标签: mysql

我正在构建一个应用,用户可以关注其他用户并进行跟踪。

用户还可以查看其他用户关注的对象。

现在让我们说 user1 正在关注 user2 关注的人,我需要找到user2所关注的所有人ID,并将其与user1关注的人进行比较。

而不是只返回与user1和user2(我在其他论坛中都看到过)匹配的所有用户的ID,我需要检索所有user2的以下ID和用户名作为一个标志,指示跟随的人是否也跟着user1。

我已经在PHP中使用每个Query的双循环,但是我担心这个代码会很昂贵,而且使用单个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);

1 个答案:

答案 0 :(得分:1)

这是一个简化的查询:

http://sqlfiddle.com/#!2/6b8d6/3

SELECT
  user.user_id,
  user.user_name,
  he.follower_id AS follower_id,
  IF(me.followed_id,1,0) AS metoo

FROM       following AS he

INNER JOIN user
   ON user.user_id = he.followed_id

LEFT  JOIN following AS me
   ON me.follower_id = 1
  AND me.followed_id = he.followed_id

WHERE he.follower_id = 2