2013-10-29 150 views
-1

此查詢是否可以工作,如果不是,我該如何將查詢放入另一個在PHP中使用PDO的查詢?SQLSTATE [42000]:語法錯誤或訪問衝突:1064

這裏是我的查詢:

$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 

回答

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]); 

您還可能發現從數據庫中獲得所需結果的方法要比使用這些相關子查詢要高效得多。

相關問題