douyanjing8287 2014-10-07 06:25
浏览 43
已采纳

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

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;
  • 写回答

1条回答 默认 最新

  • dth981485742 2014-10-07 06:53
    关注

    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];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条