試試這個:
SELECT
`date`,
SUM(IF(za_type=1,nb,0)) as sum1,
SUM(IF(za_type=2,nb,0)) as sum2,
SUM(IF(za_type=3,nb,0)) as sum3
FROM (
SELECT b.`date`,1 as za_type, COUNT(*) as nb FROM `subtable1` AS b WHERE b.`date` IN ('31-05-2013','30-05-2013','29-05.2013') UNION
SELECT c.`date`,2 as za_type, COUNT(*) as nb FROM `subtable2` AS c WHERE c.`date` IN ('31-05-2013','30-05-2013','29-05.2013') UNION
SELECT d.`date`,3 as za_type, COUNT(*) as nb FROM `subtable3` AS d WHERE d.`date` IN ('31-05-2013','30-05-2013','29-05.2013')
) as tmp
GROUP BY
`date`
UPDATE:如果需要最後30天,你可以添加此條件的date >= NOW() - INTERVAL 30 DAY
代替date IN (..)
UPDATE2:使用了新的要求(該查詢最後3天):
SELECT
za_day,
(SELECT COUNT(*) FROM subtable1 s WHERE s.date = za_day) as sum1,
(SELECT COUNT(*) FROM subtable2 s WHERE s.date = za_day) as sum2,
(SELECT COUNT(*) FROM subtable3 s WHERE s.date = za_day) as sum3
FROM (
SELECT DATE(NOW()) - INTERVAL 1 DAY as za_day UNION
SELECT DATE(NOW()) - INTERVAL 2 DAY as za_day UNION
SELECT DATE(NOW()) - INTERVAL 3 DAY as za_day
) as td
您可以使用UNION。您不能在from子句中使用日期值。 –
不,我只需要遍歷通過php生成的「一些日期值」。我不想爲每個日期觸發單個查詢,我認爲最好在單個查詢中執行此操作。 –
我甚至不明白你假裝要做什麼 – AAlferez