Answer the question
In order to leave comments, you need to log in
How to create a query from 3 tables?
there are 3 tables, their fields are the same, there is a date field, how to calculate and group the number of records by date?
counter
init
response
I got it with the 1st table
SELECT COUNT(*) as cnt, date as cdate FROM init GROUP BY date ORDER BY date DESC LIMIT 10
result
but I need to display something similar, but from 3 tables
and accordingly if in table 2 does not have the same date as in table 1, then it simply displays 0
Answer the question
In order to leave comments, you need to log in
SELECT `dates`.`date`, IFNULL(`t1`.`count`, 0) AS `cnt1`,
IFNULL(`t2`.`count`, 0) AS `cnt2`, IFNULL(`t3`.`count`, 0) AS `cnt3`
FROM (
SELECT `date` FROM `table1`
UNION SELECT `date` FROM `table2`
UNION SELECT `date` FROM `table3`
) AS `dates`
LEFT JOIN (
SELECT `date`, COUNT(*) AS `count` FROM `table1` GROUP BY `date`
) AS `t1` ON `t1`.`date` = `dates`.`date`
LEFT JOIN (
SELECT `date`, COUNT(*) AS `count` FROM `table2` GROUP BY `date`
) AS `t1` ON `t2`.`date` = `dates`.`date`
LEFT JOIN (
SELECT `date`, COUNT(*) AS `count` FROM `table3` GROUP BY `date`
) AS `t1` ON `t3`.`date` = `dates`.`date`
ORDER BY `dates`.`date`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question