A
A
Alexey Semenyuk2015-10-10 14:38:01
MySQL
Alexey Semenyuk, 2015-10-10 14:38:01

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
434c1c47d1.jpg
but I need to display something similar, but from 3 tables
7e2468897a83453e9a0c7e6da8000564.png
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

1 answer(s)
R
Rsa97, 2015-10-10
@Rsa97

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 question

Ask a Question

731 491 924 answers to any question