从多个表的Mysql查询中统计总数

时间:2019-02-14 07:05:23

标签: mysql sql database database-design relational-database

我有一个列表表,基本上每个部分都包含相同的字段。

- p_xl_cj_ticket_m_site_data      |  - p_xl_cj_ticket     |  - p_xl_cj_ticket_last_row_ingroup
- p_xl_jabo1_ticket_m_site_data   |  - p_xl_jabo1_ticket  |  - p_xl_jabo1_ticket_last_row_ingroup
- p_xl_jabo2_ticket_m_site_data   |  - p_xl_jabo2_ticket  |  - p_xl_jabo2_ticket_last_row_ingroup

如果我要计算ticket1,ticket2,ticket3中的所有网站总数,该怎么办?

  

预期输出(以上3个表的总和):

enter image description here

当前代码:

SELECT COUNT( * ) AS tot_sites, 
       IFNULL( COUNT( 
            CASE WHEN p_xl_cj_m_site_data.m_date_target = DATE( NOW( ) ) 
            THEN 1 ELSE NULL END ) , 0 ) AS todays_target, 
       IFNULL( COUNT( 
            CASE WHEN (p_xl_cj_m_site_data.m_date_target = DATE( NOW( ) ) 
                       AND p_xl_cj_ticket.t_status =9 ) 
            THEN 1 ELSE NULL END ) , 0) AS todays_achieve, 
       IFNULL( COUNT( 
            CASE WHEN p_xl_cj_ticket.t_status =9
            THEN 1 ELSE NULL END ) , 0 ) AS tot_in
FROM p_xl_cj_m_site_data
LEFT JOIN p_xl_cj_ticket_last_row_ingroup  
        ON p_xl_cj_ticket_last_row_ingroup.t_m_id = p_xl_cj_m_site_data.m_id
       AND p_xl_cj_ticket_last_row_ingroup.t_req_type =  '04_int_finish_ack'
LEFT JOIN p_xl_cj_ticket 
        ON p_xl_cj_ticket.t_id = p_xl_cj_ticket_last_row_ingroup.t_id
WHERE p_xl_cj_m_site_data.m_status =1

样本数据:

p_xl_cj_ticket_m_site_data       p_xl_cj_ticket        p_xl_cj_ticket_last_row_ingroup     
------------------------------------------------------------------------------------  
* m_date_target = 2019-02-13    * t_status = 9         * t_m_id = xxxxx123
* m_status = 1                  * t_id = abc           * t_id = abc
* m_id = xxxxx123                                      * t_req_type = 04_int_finish_ack

我当前的代码只是p_xl_cj的票。

如果要使输出像我的期望一样,该怎么办?

谢谢...

1 个答案:

答案 0 :(得分:0)

SELECT  (
    SELECT COUNT(*)
    FROM   <table>
    ) AS count1,
    (
    SELECT COUNT(*)
    FROM   <table>
    ) AS count2