按日期比较不同表中的行数

时间:2015-07-31 06:00:37

标签: php mysql json

我想将MySQL查询连接到PHP或JSON折线图(每个日期的记录数),多行(Topic1,Topic2)。

Topic1 MySQL表示例:

 created_at           |  text    
------------------------------------------------
 2015-07-21 10:10:40  |  hello this is a text
 2015-07-23 06:12:45  |  text number 2
 2015-07-23 10:12:45  |  text number 3
 2015-07-24 10:17:50  |  blah blah

Topic2 MySQL表示例:

 created_at           |  text    
-----------------------------------------------------
 2015-07-21 10:13:23  |  hello this is another text
 2015-07-22 06:12:25  |  text number 4
 2015-07-23 10:13:09  |  text number 5
 2015-07-24 12:58:27  |  blah blah blah

所以我想创建一个新表来显示图表。

图表的新表格(table_count)的预期输出:

 Date        |  Topic1    | Topic2    
-----------------------------------------------------
 2015-07-21  |    1       |    1
 2015-07-22  |   NULL     |    1
 2015-07-23  |    2       |    1
 2015-07-24  |    1       |    1

我试过这个MySQL查询

INSERT INTO table_count (Date, Topic1)
SELECT date_format(created_at,'%y-%m-%d') AS Date , COUNT(*)  
FROM Topic1
GROUP BY Date;

INSERT INTO table_count (Date, Topic2)
SELECT date_format(created_at,'%y-%m-%d') AS Date , COUNT(*)  
FROM Topic2
GROUP BY Date;

但输出将是

 Date        |  Topic1    | Topic2    
-----------------------------------------------------
 2015-07-21  |    1       |   NULL
 2015-07-23  |    2       |   NULL
 2015-07-24  |    1       |   NULL
 2015-07-21  |   NULL     |    1
 2015-07-22  |   NULL     |    1
 2015-07-23  |   NULL     |    1
 2015-07-24  |   NULL     |    1

提前谢谢!

修改(已解决):

SELECT a.Date, IFNULL(a.Count,'0') as Topic1, IFNULL(b.Count,'0') as Topic2
FROM
(SELECT date_format(created_at, '%y-%m-%d') as Date, COUNT(*) as Count FROM Topic1 GROUP BY Date) a
LEFT JOIN
(SELECT date_format(created_at, '%y-%m-%d') as Date, COUNT(*) as Count FROM Topic2 GROUP BY Date) b
ON a.Date = b.Date;

1 个答案:

答案 0 :(得分:0)

这里有一个示例,您可以在其中连接两个表的结果:

select a.Date, a.Count as Topic1, b.Count as Topic2
from
    (select date_format(created_at, '%y-%m-%d') as Date, COUNT(*) as Count
        from Topic1 group by Date) a
    outer join
    (select date_format(created_at, '%y-%m-%d') as Date, COUNT(*) as Count
        from Topic2 group by Date) b
    on a.Date = b.Date

编辑:添加外部联接以在一个主题中获取具有NULL的行。