"交叉加入" 2个查询

时间:2016-04-05 08:58:03

标签: mysql

我有2个查询:

我希望并排显示这些查询的结果(即11月的计数和12月的计数):

查询1:

SELECT 
      count(playsms_tblsmsoutgoing.uid) 
  FROM 
      playsms_tbluser 
    LEFT JOIN 
      playsms_tblsmsoutgoing
    ON 
      playsms_tblsmsoutgoing.uid = playsms_tbluser.uid 
   AND 
      MONTH(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 11 
   AND     
      YEAR(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 2015 
 WHERE 
      playsms_tbluser.flag_deleted = 0 
GROUP BY 
      playsms_tbluser.name`

查询2:

SELECT 
      count(playsms_tblsmsoutgoing.uid) 
  FROM 
      playsms_tbluser 
    LEFT JOIN 
      playsms_tblsmsoutgoing
    ON
      playsms_tblsmsoutgoing.uid = playsms_tbluser.uid 
   AND 
      MONTH(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 12 
   AND
      YEAR(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 2015 
 WHERE 
      playsms_tbluser.flag_deleted = 0 
GROUP BY 
      playsms_tbluser.name`

有可能吗?如果有,怎么样?在此期间我将谷歌搜索解决方案。

1 个答案:

答案 0 :(得分:0)

你需要为每个表创建一个别名,然后使用一些id将它们连接在一起,在下面的示例查询中,我将使用playsms_tbluser.name作为两个表的比较。

SELECT nov.name, countNov, countDec FROM
(
    SELECT playsms_tbluser.name, count(playsms_tblsmsoutgoing.uid) as countNov
    FROM playsms_tbluser LEFT JOIN playsms_tblsmsoutgoing
    ON playsms_tblsmsoutgoing.uid = playsms_tbluser.uid 
    AND MONTH(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 11 AND YEAR(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 2015 
    WHERE playsms_tbluser.flag_deleted = 0 
    GROUP BY playsms_tbluser.name
) as nov
INNER JOIN
(
    SELECT playsms_tbluser.name, count(playsms_tblsmsoutgoing.uid)  as countDec
    FROM playsms_tbluser LEFT JOIN playsms_tblsmsoutgoing
    ON playsms_tblsmsoutgoing.uid = playsms_tbluser.uid 
    AND MONTH(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 12 AND YEAR(STR_TO_DATE(p_datetime, '%Y-%m-%d')) = 2015 
    WHERE playsms_tbluser.flag_deleted = 0 
    GROUP BY playsms_tbluser.name
) as dec ON nov.name = dec.name