문제

I have the following PHP code which whows a weird behaviour. The system is backed by a PostgreSQL database, PHP version is 5.3.15.

    $sql = "SELECT ce.id FROM calendar_events AS ce
        WHERE ce.rowid = :rowid
        AND ((SELECT count(*) FROM calendar_events_attendees AS cea WHERE cea.event_id = ce.id AND cea.status <> 'D') > 0
            OR (SELECT count(*) FROM calendar_events_globalfnbl AS ceg WHERE ceg.event_id = ce.id AND ceg.status <> 'D') > 0)";

$stmt = db_prepare($sql); // Creates a PDOStatement
$stmt->bindValue(":rowid", $rowid, PDO::PARAM_INT);
$rv = $stmt->execute();

if($rv) {
    return $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
}
else {
    return null;
}

The query executes without errors but the function returns an empty array. There are definitely rows to find in the database, if I execute the query in pgAdmin (placeholder replaced by ID in question of course), it returns the rows I want to get.

I managed to find out that the sub-queries are the problem here. If I comment them out and use the following query, the rows are returned. But of course this does also return rows which I try to filter out with the sub-queries.

$sql = "SELECT ce.id FROM calendar_events AS ce
        WHERE ce.rowid = :rowid";

Does PDO simply not support this type of sub-queries or is there any error in my code I cannot find?

Thanks in advance!

도움이 되었습니까?

해결책 2

This was not a problem with PDO but with my code itself. After double checking the code calling the above function again and again I found some statements that set the status to 'D' for the rows in question BEFORE the above code was executed.

So this question is now obsolete, sorry for wasting your time folks!

다른 팁

I don't know about your framework, but your COUNT(*) > 0 subqueries appear to be equivalent to EXISTS (...) subqueries (which might be faster as well, since they don't have to count all satisfying tuples)

SELECT ce.id 
FROM calendar_events AS ce
WHERE ce.rowid = :rowid
AND ( EXISTS (SELECT *
                FROM calendar_events_attendees AS exa
                WHERE exa.event_id = ce.id AND exa.status <> 'D'
                )
     OR EXISTS (SELECT * 
                FROM calendar_events_globalfnbl AS exg
                WHERE exg.event_id = ce.id AND exg.status <> 'D'
                )
        );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top