这个MySQL查询有什么问题

时间:2014-01-15 13:42:41

标签: php mysql pdo

  public function getfriends($username){        

    //  gets a users friends by username... does cross checking and joins the users table to it so we can get other data without having to do another query
        $sql = "SELECT S.ts, S.stats, S.image, PI.rusername, PI.arefriend,
                       PI.tusername AS friend
                FROM friends PI
                JOIN users S ON PI.tusername = S.username
                WHERE S.username = PI.tusername
                AND PI.tusername!=:username
                AND PI.rusername=:username
                AND S.username!=:username
                UNION
                SELECT S.ts, S.stats, S.image, PI.tusername, PI.arefriend,
                       PI.rusername AS friend
                FROM friends PI
                JOIN users S ON PI.rusername = S.username
                WHERE S.username = PI.rusername
                AND PI.rusername!=:username
                AND PI.tusername=:username";

        $stmt = db::prepare($sql);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();

        if($stmt->rowCount())
        {
            // Loop through the assoc array and create a new array we can return
            // after processing is done.

// fetch assoc as suggested by Jon removes the duplicates
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $xrow[]=$row;
            }
            return $xrow;   
        } elseif(!$stmt->rowCount()) {
            return 0;
        }
    }

这是我的函数,它是一个类的一部分,你基本上给它一个用户名,它选择该用户的所有朋友,并将它们放在一个数组中。因此,无论何时调用此函数形式,我都可以遍历结果。朋友数据库表中的这两列名为tusername和rusername。这基本上是跟踪谁向朋友发送了一个请求。它是tousername和requestusername的缩写。

现在有些值丢失了,这是返回数据的原理

  Array
(
    [0] => Array
        (
            [ts] => 2014-01-15 08:27:17
            [stats] => 
            [image] => uploads/girl.jpg
            [rusername] => nasser
            [arefriend] => 2
            [friend] => girl
        )

)

正如你所看到的那样,rusername存在,但tusername缺失,tusername中的数据错误膨胀,只显示传递给getfriends函数的用户名。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我不知道你为什么在这里使用工会。

试试这个

   SELECT S.ts, S.stats, S.image, PI.rusername, PI.arefriend,
               PI.tusername AS friend
        FROM friends PI
        JOIN users S ON PI.tusername = S.username
        WHERE S.username!=:username