合并内部选择和计数不起作用

时间:2014-12-03 22:33:42

标签: php mysql pdo

为什么我会通过此查询获得此结果?

{"num_added":null,"num_completed":"0","num_liked":"0","following":"1","followers":"0","success":1}

“num_added”应为0而不是null。

try {
        $stmt = $conn->prepare("
        SELECT

        COALESCE((SELECT COUNT(ID) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS ADDED,
        COALESCE((SELECT SUM(CASE WHEN USERS_BUCKETS.STATUS='Completed' THEN 1 ELSE 0 END) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS DONE,
        COALESCE((SELECT COUNT(ID) FROM USERS_LIKES WHERE USERS_LIKES.USERID = USERS.ID),0) AS NUM_LIKES,
        COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.USER_ID=USERS.ID),0) AS FOLLOWING,
        COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.FOLLOW_ID=USERS.ID),0) AS FOLLOWERS

        FROM USERS 
        WHERE USERS.ID=?");

        $stmt -> execute(array($userid));
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                $response["num_added"]= $row['ADDED'];
                $response["num_completed"]= $row['DONE'];
                $response["num_liked"]= $row['NUM_LIKES'];
                $response["following"]= $row['FOLLOWING'];
                $response["followers"]= $row['FOLLOWERS'];

            }
            $response["success"] = 1;
        } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
        $response["success"] = 0;
    }

0 个答案:

没有答案