I have two tables:
Table 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
So from this table I want to get count field Id
for each day.
For this I use next query:
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;
It's work good.
So next table is 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
To select data by date from this table I use next query:
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;
It's also work good. So my purpose is merge these two queries into one SELECT
that next I can write in php one tables with count of Id
by date from table t1
and with count of count
field from table t2
by date.
When I try next query:
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;
It's not work. What I do wrong?
Unfortunately, groupby function does not allow you to use multiple table columns, you can only use one table which defined in the function table parameter. You can consider using SUMMARIZECOLUMNS function, it allows you to group records based on different table fields.
In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.
First you should UNION these results and then group by days and select aggregate fields. Also you can JOIN these queries but it can be a problem if some days miss in one of two tables:
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
SQL fiddle demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With