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

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿