-1

这个查询应该工作吗?如果没有,我怎么能在 PHP 中使用 PDO 将一个查询放入另一个查询?

这是我的查询:

$userid = array($users->school_name_from_id($_SESSION['user_id']), $_SESSION['user_id'], $_SESSION['user_id']);
$statementString =
  'SELECT * FROM schoolinfo 
   WHERE schoolinfo.school = ? AND 
     SELECT count(*) FROM friendstable 
       WHERE friendstable.user_ID = ? 
        AND frienstable.friend_ID = schoolinfo.id  <= 0
   AND 
     SELECT count(*) FROM friendstable 
     WHERE friendstable.user_ID = schoolinfo.id 
       AND friendstable.friend_ID = ?  <= 0 
   ORDER BY RAND()
   LIMIT 6';


        $stmt = $database->_link->prepare($statementString);
        $stmt->execute($userid);
        $array = $stmt->fetchAll(PDO::FETCH_ASSOC);
        print_r($array);

这是我在运行时得到的完整错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT count(*) FROM friendstable WHERE friendstable.user_ID = '1' AND frienstab' at line 1' in C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php:20 Stack trace: #0 C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php(20): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\thinkaztech\PHP\getSocialInformation.php on line 20
4

1 回答 1

1

子查询必须放在括号内:

SELECT   *
FROM     schoolinfo
WHERE    schoolinfo.school = ?
     AND (
           SELECT COUNT(*)
           FROM   friendstable
           WHERE  friendstable.user_ID   = ?
              AND friendstable.friend_ID = schoolinfo.id
         ) <= 0
     AND (
           SELECT COUNT(*)
           FROM   friendstable
           WHERE  friendstable.user_ID   = schoolinfo.id
              AND friendstable.friend_ID = ?
         ) <= 0
ORDER BY RAND()
LIMIT    6

请注意,在这种情况下,您必须将一个二元素数组传递给该PDO::execute()方法:

$stmt->execute([$userid, $userid]);

您可能还会发现,与使用这些相关子查询相比,从数据库中获取所需结果的方法要有效得多。

于 2013-10-29T20:51:19.590 回答