user756659
user756659

Reputation: 3512

group subquery counts in mysql statement?

Wondering if this is possible or not. In the statement below I am getting counts from different tables. This prints our an array of totals for each user_id.

Is there any way to combine these totals so it returns a single array with the totals? I am using subqueries as joins were taking a hit performance-wise so joining is not an option.

$stmt = $db->prepare("
    SELECT
        (SELECT COUNT(*) FROM log1 WHERE log1.user_id = users.user_id AS l1,
        (SELECT COUNT(*) FROM log2 WHERE log2.user_id = users.user_id AS l2,
        (SELECT COUNT(*) FROM log3 WHERE log3.user_id = users.user_id AS l3,
        (SELECT COUNT(*) FROM log4 WHERE log4.user_id = users.user_id  AS l4
    FROM computers
    INNER JOIN users
        ON users.computer_id = computers.computer_id    
    WHERE computers.account_id = :cw_account_id AND computers.status = :cw_status
");

$binding = array(
    'cw_account_id' => $_SESSION['user']['account_id'],
    'cw_status' => 1
);

$stmt->execute($binding);

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

At the moment I am doing something like this with the return to get the result I want:

foreach($result as $key)
{
    $new['l1'] = $new['l1'] + $key['l1'];
    $new['l2'] = $new['l2'] + $key['l2'];
    $new['l3'] = $new['l3'] + $key['l3'];
    $new['l4'] = $new['l4'] + $key['l4'];
}

return $new;

Upvotes: 0

Views: 85

Answers (1)

Rimas
Rimas

Reputation: 6024

Use SUM aggregate function:

$stmt = $db->prepare("
    SELECT
        SUM((SELECT COUNT(*) FROM log1 WHERE log1.user_id = users.user_id)) AS l1,
        SUM((SELECT COUNT(*) FROM log2 WHERE log2.user_id = users.user_id)) AS l2,
        SUM((SELECT COUNT(*) FROM log3 WHERE log3.user_id = users.user_id)) AS l3,
        SUM((SELECT COUNT(*) FROM log4 WHERE log4.user_id = users.user_id)) AS l4
    FROM computers
    INNER JOIN users
        ON users.computer_id = computers.computer_id    
    WHERE computers.account_id = :cw_account_id AND computers.status = :cw_status
");

This query returns one row with total counts and your required result:

$new = $result[0];

Upvotes: 1

Related Questions