我有两张桌子:
表t1:
id | date_click
1 | 2016-02-31 17:17:23
2 | 2016-03-31 12:11:21
3 | 2016-03-31 13:13:23
因此,从这张表中我想得到每天的计数字段Id
。
为此,我使用下一个查询:
SELECT date_format(date_click, '%Y-%m-%d') as date_click_event
, COUNT(id) as count_click
FROM t1
GROUP
BY date_click_event
ORDER
BY date_click_event DESC;
这很好用。
所以下一个表是t2。
id | count | date_sent
1 | 33 | 2016-02-31 11:12:23
2 | 22 | 2016-03-31 14:11:22
3 | 11 | 2016-03-31 13:12:13
要从此表中按日期选择数据,我使用下一个查询:
SELECT date_format(date_sent, '%Y-%m-%d') as date_sent_push
, SUM(count) as count_sent
FROM t2
GROUP
BY date_sent_push
ORDER
BY date_sent_push DESC
LIMIT 100;
它也很好用。所以我的目的是将这两个查询合并为一个SELECT
,然后我可以在php中写一个表Id
的表,按表t1
的日期计算,并且计数为count
表格t2
中的字段按日期显示。
当我尝试下一个查询时:
SELECT date_format(t2.date_sent, '%Y-%m-%d') AS date_sent_push
, SUM(t2.count) as count_sent
, COUNT(t1.id) as count_click
FROM t2
, t1
WHERE date_format(t2.date_sent, '%Y-%m-%d') = date_format(t1.date_click, '%Y-%m-%d')
GROUP
BY date_sent_push
ORDER
BY date_sent_push
DESC
LIMIT 100;
这不行。我做错了什么?
答案 0 :(得分:4)
首先,您应该UNION这些结果,然后按天分组并选择聚合字段。您也可以加入这些查询,但如果有两天在两个表之一中错过,则可能会出现问题:
SELECT date_sent_push,
MAX(count_click) as count_click,
MAX(count_sent) as count_sent
FROM
(SELECT date_format(date_click, '%Y-%m-%d') as date_sent_push
, COUNT(id) as count_click
, NULL as count_sent
FROM t1
GROUP BY date_sent_push
UNION ALL
SELECT date_format(date_sent, '%Y-%m-%d') as date_sent_push
, NULL as count_click
, SUM(count) as count_sent
FROM t2
GROUP
BY date_sent_push
) as t3
GROUP BY date_sent_push
答案 1 :(得分:0)
use this code
(SELECT date_format(date_sent, '%Y-%m-%d') as date_sent_push, SUM(count) as count_sent FROM t2 GROUP BY date_sent_push ORDER BY date_sent_push DESC LIMIT 100)
UNION
(SELECT date_format(t2.date_sent, '%Y-%m-%d') AS date_sent_push, SUM(t2.count) as count_sent, COUNT(t1.id) as count_click FROM t2, t1 WHERE date_format(t2.date_sent, '%Y-%m-%d')=date_format(t1.date_click, '%Y-%m-%d') GROUP BY date_sent_push ORDER BY date_sent_push DESC LIMIT 100)