使用各种条件和表格获取/优化计数

时间:2014-06-04 20:35:22

标签: mysql

我试图在一次通话中返回不同条件和表格的计数。我以前在自己的子查询中都有这些中的每一个,但是意识到查询realtime_logs表4次没有意义......所以我把它改成了下面的stmt,按预期工作。

$stmt = $db->prepare("
    SELECT
        sum(case when event_title = 'opened' then 1 end) as opened, 
        sum(case when event_title = 'closed' then 1 end) as closed,
        sum(case when event_title = 'viewed' then 1 end) as viewed,
        sum(case when event_title LIKE '%blocked%' then 1 end) as blocked 
    FROM realtime_logs
");
$stmt->execute();

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

这样做虽然我失去了从其他桌子获取计数的能力......我想要这样的东西......

$stmt = $db->prepare("
        SELECT
            sum(case when event_title = 'opened' then 1 end) as opened, 
            sum(case when event_title = 'closed' then 1 end) as closed,
            sum(case when event_title = 'viewed' then 1 end) as viewed,
            sum(case when event_title LIKE '%blocked%' then 1 end) as blocked 
        FROM realtime_logs

       // I also want to return the count for this different table

       (SELECT COUNT(location_id)
        FROM spc_location_logs
       ) as locations
");

2 个答案:

答案 0 :(得分:1)

为什么你不能简单地分成两个语句/查询?您可以在之后使用PHP将返回值合并到一个数组中。试试这个:

$stmt1 = $db->prepare("
    SELECT
        sum(case when event_title = 'opened' then 1 end) as opened, 
        sum(case when event_title = 'closed' then 1 end) as closed,
        sum(case when event_title = 'viewed' then 1 end) as viewed,
        sum(case when event_title LIKE '%blocked%' then 1 end) as blocked,
    FROM realtime_logs
");

$stmt2 = $db->prepare('
    SELECT COUNT(location_id) AS locations
    FROM spc_location_logs
');

$stmt1->execute();
$stmt2->execute();

$arr1 = $stmt1->fetchAll(PDO::FETCH_KEY_PAIR);
$arr2 = $stmt2->fetchAll(PDO::FETCH_KEY_PAIR);

$arr  = array_merge($arr1, $arr2);

请注意我使用FETCH_KEY_PAIR模式。

答案 1 :(得分:1)

一种是将第二个计数查询作为子查询放在SELECT列表中:

SELECT SUM(event_title = 'opened') AS opened,
       SUM(event_title = 'closed') AS closed,
       SUM(event_title = 'viewed') AS viewed,
       SUM(event_title LIKE '%blocked%') AS blocked,
       (SELECT COUNT(*) from spc_location_logs) AS locations
FROM realtime_logs

第二个是加入:

SELECT SUM(r.event_title = 'opened') AS opened,
       SUM(r.event_title = 'closed') AS closed,
       SUM(r.event_title = 'viewed') AS viewed,
       SUM(r.event_title LIKE '%blocked%') AS blocked,
       l.locations
FROM realtime_logs AS r
CROSS JOIN 
    (SELECT COUNT(*) AS locations
     FROM spc_location_logs) AS l

第二种方法更灵活一点 - 你可以在第二个查询中有多个计数并将它们全部显示出来。

顺便说一句,你通常应该使用COUNT(*)而不是COUNT(column_name),除非该列可能包含空值而你不需要计算它们。