MYSQL连接两个表与两列

时间:2015-09-02 12:35:05

标签: mysql

我有两张桌子 1)用户(ID,registerdate) 2)user_answer(用户ID,应答,updated_date)

我想要每天零使用次数。有多少用户正在注册但每天都没有回复。结果将是这样的:

Date        registedCount   notAnsweredCount

15-09-02    20              10
15-09-01    20              10
15-08-31    12              4

提前致谢。

2 个答案:

答案 0 :(得分:0)

使用IF语句结果的SUM: -

SELECT date_range.aDay, 
        COUNT(DISTINCT users.id) AS registedCount, 
        SUM(IF(users.id IS NOT NULL AND user_answer.userid IS NULL, 1, 0)) AS notAnsweredCount
FROM
(
    SELECT DATE_ADD('2015-09-01', INTERVAL units.aCnt + tens.aCnt * 10 DAY) AS aDay
    FROM
    (
        SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) units
    CROSS JOIN
    (
        SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 
    ) tens
) date_range
LEFT OUTER JOIN users
ON date_range.aDay = users.registerdate
LEFT OUTER JOIN user_answer
ON users.id = user_answer.userid
GROUP BY date_range.aDay

这样可以添加一系列数字来添加日期,以提供一系列日期(在这种情况下,从9月1日起包含100天)。然后,对于在注册日期匹配的用户,这是LEFT OUTER JOIN,然后是针对user_answer的LEFT OUTER JOIN。它计算了不同的user.id来获取在每个日期注册的人数,并总结了user_answer中的用户ID为NULL的位置(即,没有回答任何问题)。

编辑 - 如果你不关心在没有用户注册的日子里在返回的数据中存在空白,并且想要一个至少有1个人注册这个的所有日子的列表,这个简单的查询将完成这项工作: -

SELECT users.registerdate, 
        COUNT(DISTINCT users.id) AS registedCount, 
        SUM(IF(user_answer.userid IS NULL, 1, 0)) AS notAnsweredCount
FROM users
LEFT OUTER JOIN user_answer
ON users.id = user_answer.userid
GROUP BY users.registerdate

答案 1 :(得分:0)

检查以下查询,它应该能为您提供所需的结果

SELECT results.date, 
    SUM(results.answered) as answered,
    COUNT(results.userid)-SUM(results.answered) as notanswered
FROM
(SELECT @id:= u.id as userid, @regdate:= u.regdate as date,
   (CASE WHEN EXISTS (SELECT 1 FROM user_answer WHERE updated_date = @regdate AND userid = @id)
    THEN 1 ELSE 0 END) AS answered
FROM users u) AS results
GROUP BY results.date