加入两个表以获取MySql中用户的总访问次数

时间:2015-11-27 10:06:39

标签: mysql

在我的MySql中,我有两个表:tblN1tblN2

tblN1是一张旧表,在网站上的受限区域内存储了帐户。

tblN2是一个新表,在网站上的受限区域内存储了帐户。

如果在tblN1上尝试此查询:

mysql> SELECT
    COUNT(*) AS TotalN1
FROM
    `tblN1`
WHERE
    UserN1 IN ('7047505')
AND dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
AND CURDATE();
+---------+
| TotalN1 |
+---------+
|       4 |
+---------+
1 row in set

此查询的返回值为4

如果在tblN2上尝试此查询:

mysql> SELECT
    COUNT(*) as TotalN2
FROM
    `tblN2`
WHERE
    UserN2 IN ('7047505')
AND dateN2 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
AND CURDATE();
+---------+
| TotalN2 |
+---------+
|       0 |
+---------+
1 row in set

此查询的返回值为0

我试图加入两个表来获取用户的总访问次数。

mysql> SELECT
    (
        COUNT(DISTINCT A.ID) + COUNT(DISTINCT CA.ID)
    ) AS SuperTotal,
    COUNT(DISTINCT A.ID) AS TotalN1,
    COUNT(DISTINCT CA.ID) AS TotalN2,
    UserN1 AS UserN1,
    UserN2  AS UserN2
FROM
    `tblN1` A
JOIN `tblN2` CA ON A.UserN1 = CA.UserN2
WHERE
    CA.UserN2 IN ('7047505')
AND (
    dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
    AND CURDATE()
    AND `dateN2` BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
    AND CURDATE()
);
+------------+---------+---------+--------+--------+
| SuperTotal | TotalN1 | TotalN2 | UserN1 | UserN2 |
+------------+---------+---------+--------+--------+
|          0 |       0 |       0 | NULL   | NULL   |
+------------+---------+---------+--------+--------+
1 row in set

所有字段的返回值为0,为什么?

请帮帮我,谢谢你。

编辑#1

mysql> SELECT sum(total) as Total FROM
    (SELECT COUNT(*) AS Total
    FROM `tblN1`
    WHERE UserN1 IN ('7047505')
          AND dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND CURDATE()
    UNION ALL
    SELECT COUNT(*)
    FROM `tblN2`
    WHERE UserN2 IN ('7047505')
          AND dateN2 BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND CURDATE()
    ) AS t;


+-------+
| Total |
+-------+
| 0     |
+-------+
1 row in set

1 个答案:

答案 0 :(得分:1)

连接会导致返回0。从您的示例中可以清楚地看出,给定用户没有满足第二个表中where条件的任何记录。当您在第二个表上加入第一个用户ID表时,第二个表中没有返回任何结果,因此该连接将从第一个表中删除相应的记录。

更新:

不是使用join,而是在子查询中将2个查询与union结合起来,并将它们添加到外部查询中:

SELECT sum(total) as Total FROM
    (SELECT COUNT(*) AS Total
    FROM `tblN1`
    WHERE UserN1 IN ('7047505')
          AND dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND CURDATE()
    UNION ALL
    SELECT COUNT(*)
    FROM `tblN2`
    WHERE UserN2 IN ('7047505')
          AND dateN2 BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND CURDATE()
    ) AS t