不同条件下不同表中两个计数的总和

时间:2015-09-25 03:49:59

标签: mysql

基本上我需要将这些合并到一个查询中:

SELECT COUNT( DISTINCT id ) AS totalRows1 
FROM other_events WHERE status = "approved" 
AND Location = 1

SELECT COUNT( DISTINCT Id ) AS totalRows2 
FROM core_events WHERE Status = "Active"
AND Location_id = 1

当我这样做时,如果没有Location_id = 1的事件,则查询返回0.在那种情况下,我需要它只返回第一个表的计数。

SELECT COUNT( DISTINCT t1.id ) + COUNT( DISTINCT t2.Id ) AS total
FROM other_events AS t1, core_events AS t2
WHERE t1.status = "approved"
AND t1.Location = 1
AND t2.Location_id = 1
AND t2.Status = 'Active'

PS。列名与上面的名称完全相同

1 个答案:

答案 0 :(得分:1)

使用UNION语句合并结果,如下所示:

SELECT SUM(total) FROM (
    SELECT COUNT(DISTINCT id) AS total
    FROM other_events
    WHERE (status = "approved" AND Location = 1)

    UNION ALL

    SELECT COUNT(DISTINCT Id) AS total
    FROM core_events
    WHERE (Location_id = 1 AND Status = 'Active')
) union_result