组子查询在mysql语句中计数?

时间:2014-10-07 06:25:25

标签: php mysql sql

想知道这是否可行。在下面的陈述中,我从不同的表中得到了计数。这将打印每个user_id的总计数组。

有没有办法合并这些总数,以便返回一个包含总数的数组?我正在使用子查询,因为连接在性能方面受到了打击,因此加入不是一种选择。

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

目前我正在做这样的事情,返回得到我想要的结果:

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;

1 个答案:

答案 0 :(得分:1)

使用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
");

此查询返回一行,包含总计数和所需结果:

$new = $result[0];