1

我有以下查询:

SELECT a.status, count(a.status) FROM
(SELECT 'Delivered' AS status
UNION ALL SELECT 'Buffered'
UNION ALL SELECT 'Not Delivered'
UNION ALL SELECT 'Not Reported') a
LEFT JOIN 
bulk_sms_numbers
ON a.status = bulk_sms_numbers.delivery_status
WHERE bulk_sms_id = 52
GROUP BY a.status;

和以下结果:

+-----------+-----------------+
|  status   | count(a.status) |
+-----------+-----------------+
| Buffered  |              10 |
| Delivered |            3200 |
+-----------+-----------------+

我希望结果集包含联合所有查询中列出的所有可能状态

我需要的示例输出。

+---------------+-----------------+
|    status     | count(a.status) |
+---------------+-----------------+
| Buffered      |              10 |
| Delivered     |            3200 |
| Not Delieverd |               0 |
| Not Reported  |               0 |
+---------------+-----------------+

我正在使用 MySql

4

4 回答 4

5

将条件从WHERE子句移入ON,以便过滤将在加入时进行,而不是在最终结果列表中。

SELECT a.status, count(a.status) 
FROM
    (
        SELECT 'Delivered' AS status
        UNION ALL SELECT 'Buffered'
        UNION ALL SELECT 'Not Delivered'
        UNION ALL SELECT 'Not Reported'
    ) a
    LEFT JOIN bulk_sms_numbers
        ON a.status = bulk_sms_numbers.delivery_status AND 
            bulk_sms_id = 52
GROUP BY a.status;
于 2013-02-05T16:23:04.910 回答
1

尝试将 WHERE 条件移入 ON 子句并使用 OUTER 连接。

SELECT a.status, count(a.status) FROM
(SELECT 'Delivered' AS status
UNION ALL SELECT 'Buffered'
UNION ALL SELECT 'Not Delivered'
UNION ALL SELECT 'Not Reported') a
LEFT OUTER JOIN 
bulk_sms_numbers
ON a.status = bulk_sms_numbers.delivery_status
AND bulk_sms_id = 52
GROUP BY a.status;
于 2013-02-05T16:24:40.580 回答
0

我最终使用了这样的查询:

SELECT cnt, IFNULL(delivery_status, 'Not Reported') delivery_status FROM (
    SELECT delivery_status, count(delivery_status) cnt FROM bulk_sms_numbers WHERE bulk_sms_id = 52 GROUP BY delivery_status
) x

然后在php中我将所有状态的默认值设置为0

$data = $db->fetchAll($q, array($aid, $reference));

$statuses = array(
    'Buffered' => 0,
    'Delivered' => 0,
    'Not Delivered' => 0,
    'Not Reported' => 0,
);

foreach ($data as $value) {
    $statuses[$value['delivery_status']] = $value['cnt'];
}

虽然这解决了我的问题,但不是我问题的答案。我想找到一个纯 sql 答案。

于 2013-03-04T20:02:59.760 回答
0

尝试也给所有列名并将其更改ON为有条件的

SELECT a.status, count(a.status) FROM
(SELECT 'Delivered' AS status
UNION ALL SELECT 'Buffered' As status
UNION ALL SELECT 'Not Delivered' as status
UNION ALL SELECT 'Not Reported' as status) a
LEFT JOIN 
bulk_sms_numbers
ON a.status = bulk_sms_numbers.delivery_status
AND bulk_sms_id = 52
GROUP BY a.status;
于 2013-02-05T16:23:31.090 回答