2013-10-06 157 views
1

我有3個表,其中包含一些記錄有一個日期和一個數值(表不能被合併)。我想用表格中的信息組成條形圖。條形圖按日期分組,並應顯示最近七天。mysql多表選擇最近7天

早些時候,我有兩個表,並使用下面的查詢方案:

SELECT 
    t.credits1, 
    t.credits2, 
    t.date 
FROM 
    (
     (
      SELECT 
       t1.credits1, 
       t2.credits2, 
       t1.date 
      FROM 
       (
        SELECT 
         SUM(credits) AS credits1, 
         date 
        FROM 
         table1 
        WHERE 
         table1.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
        GROUP BY 
         DATE(table1.date) 
       ) t1 

       LEFT JOIN 
       (
        SELECT 
         SUM(credits) AS credits2, 
         date 
        FROM 
         table2 
        WHERE 
         table2.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
        GROUP BY 
         DATE(table2.date) 
       ) t2 
       ON t1.date = t2.date 
     ) 
     UNION 
     (
      SELECT 
       t1.credits1, 
       t2.credits2, 
       t1.date 
      FROM 
       (
        SELECT 
         SUM(credits) AS credits1, 
         date 
        FROM 
         table1 
        WHERE 
         table1.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
        GROUP BY 
         DATE(table1.date) 
       ) t1 

       RIGHT JOIN 
       (
        SELECT 
         SUM(credits) AS credits2, 
         date 
        FROM 
         table2 
        WHERE 
         table2.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
        GROUP BY 
         DATE(table2.date) 
       ) t2 
       ON t1.date = t2.date 
     ) 
    ) t GROUP BY 
DATE(date) 

(僞代碼)

但我怎麼能做到這一點有超過2個表? 是否有機會將過去7天的日期設置爲基準,以便每次獲得7條記錄?

指出問題:如果我沒有記錄在第一張表中的一天,我不會從那天的其他表中獲取記錄。

回答

2

我假設3個表具有相似的模式?嘗試使用UNION ALL將表連接在一起。

SELECT ABB1.date, SUM(ABB1.credit) AS daily_total 
FROM 
    (SELECT date, credits 
    FROM table1 

    UNION ALL 

    SELECT date, credits 
    FROM table1 

    UNION ALL 

    SELECT date, credits 
    FROM table2) AS ABB1 
WHERE DATE >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
+0

非常感謝。 :) – Iwan1993