PDO MySQL使用select插入多行

时间:2015-04-02 16:56:11

标签: mysql pdo

我有一张桌子用于存储跟随他人的人,另一张用于存储有某本书的人。

这就是我能做的:

列出关注$ userid的用户

$bookid = '000016';
$userid = '0000000000000156';
    try {
        $stmt = $conn->prepare("SELECT FOLLOW.USER_ID FROM FOLLOW WHERE FOLLOW.FOLLOW_ID = ?");
        $stmt -> execute(array($userid));       
        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
            $output[] = $row;
            $response["success"] = 1;
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
        $response["success"] = 0;
    }

列出拥有$ bookid

的用户
try {
    $stmt = $conn->prepare("SELECT USERS_BOOKS.USERID FROM USERS_BOOKS WHERE USERS_BOOKS.BOOKID = ?");
    $stmt -> execute(array($bookid));       
    while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
        $output2[] = $row;
        $response["success"] = 1;
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
    $response["success"] = 0;
}

现在我想将这些插入到一个跟随$ userid且有$ bookid的新表中。这是我尝试使用不同版本的内容:

try {
    $stmt = $conn->prepare("INSERT INTO NOTI_COMPLETE2 (USERID_OWNER, USERID_COMPLETER, BOOKID)
        SELECT FOLLOW.USERID FROM FOLLOW
        LEFT JOIN USERS_BOOKS ON USERS_BOOKS.USERID = FOLLOW.USERID
        WHERE FOLLOW.FOLLOW_ID = ? AND USERS_BOOKS.BOOKID = ?, ?, ?");
        $query_params = array($userid, $bookid, $userid, $bookid);  
    $stmt->execute($query_params); 
    $response["success"] = 1;
    } catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

所以结果应该是这样的

ID, USERID_OWNER, USERID_COMPLETER, BOOKID
01, 000000000001, 0000000000000156, 000016
01, 000000000011, 0000000000000156, 000016
01, 000000000078, 0000000000000156, 000016
01, 000000000105, 0000000000000156, 000016

表示该表包含那些跟随USERID_COMPLETER且具有BOOKID的USERID_OWNER。

这引发了一个错误(我猜这是无关紧要的,因为谁知道如何做到这一点,看到了问题)。

2 个答案:

答案 0 :(得分:0)

您错过了 VALUES(''''''),它应该从中获取正好3列你的SELECT语句,

因为我不确定USERID_COMPLETER。您必须将确切的'table-name'.'column-name'放在那里

  INSERT INTO NOTI_COMPLETE2 (`USERID_OWNER`, `USERID_COMPLETER`, `BOOKID`)
    VALUES ( SELECT FOLLOW.USERID, FOLLOW.FOLLOW_ID, USERS_BOOKS.BOOKID FROM FOLLOW
            LEFT JOIN USERS_BOOKS ON USERS_BOOKS.USERID = FOLLOW.USERID
            WHERE FOLLOW.FOLLOW_ID = ? AND USERS_BOOKS.BOOKID = ?);

答案 1 :(得分:0)

try {
        $stmt = $conn->prepare("INSERT INTO NOTI_COMPLETE2 (USERID_OWNER, USERID_COMPLETER, BOOKID)
     SELECT FOLLOW.USER_ID, ?, ?, ? FROM FOLLOW
            LEFT JOIN USERS_BOOKS ON USERS_BOOKS.USERID = FOLLOW.USER_ID
            WHERE FOLLOW.FOLLOW_ID = ? AND USERS_BOOKS.BOOKID = ?");
            $query_params = array($userid, $bookid, $userid, $bookid);  
        $stmt->execute($query_params); 
        $response["success"] = 1;
        } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }