2014-10-07 42 views
0

想知道這是否可能。在下面的聲明中,我從不同的表中獲得計數。這會打印我們每個user_id的總計數組。組子查詢在mysql語句中計數?

有什麼辦法可以合併這些總數,所以它返回一個總數與單個數組?我正在使用子查詢,因爲連接的性能明智,因此連接不是一種選擇。

$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

使用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]; 
+0

SUM()如何在這裏添加任何值?這是完全一樣的結果。 – 2014-10-07 07:10:51

+0

@Used_By_Already原始查詢爲每個用戶返回許多行。用SUM查詢返回一行 - 所以結果不一樣。如果使用這個查詢,然後循環'foreach($ result爲$ key)...'不是必需的。 – Rimas 2014-10-07 07:19:35

+0

然後完全刪除電腦和用戶表?也許我不明白;如果很抱歉 – 2014-10-07 07:21:50