MySQL建立臨時表應用

有的時候我們的數據表結構是這樣的

currentdate counts

2011-07-12 15

2011-07-13 35

2011-07-14 43

2011-07-24 34

2011-07-25 12

2011-07-28 25

2011-07-29 34

2011-08-16 45

2011-08-17 85

2011-08-18 23

稱這個表為A表,這是我們需要統計出A表 2011-07-01 到 2011-08-31 這兩個月的每天的counts值。但是我們發現2011-07-01到2011-08-01, 2011-07-26到2011-07-27,2011-08-19到2011-08-31,這些地方是空的,也就是斷行了,沒有數據的,所以說如果要給這些地方返回 counts=0 在PHP中處理就顯得非常的麻煩。

Advertisements

然而我們就可以在MySQL中創建一個臨時表,該表內裡面的的信息為

currentdate

2011-07-01

2011-07-02

2011-07-03

2011-08-29

2011-08-30

2011-08-31

稱這個表為B表,因此只要A右鏈接B表,就能返回新的數據結果集。而且Mysql也提供在內存中創建臨時表,但mysql鏈接釋放的時候這個表也消失了。這不失為一個好辦法,但是我沒有測試過讀寫效率。

//Type=heap$this->DB->query("CREATE TEMPORARY TABLE IF NOT EXISTS tmp_table(tmp_currentdate varchar(10) NOT NULL) TYPE = HEAP");//設置插入數據用的SQL語句$insertSql = "INSERT INTO tmp_table(tmp_currentdate) VALUES";//插入數據$this->startTime = mktime(0, 0, 0 ,7, 1, 2011);$this->endTime = mktime(0, 0, 0 ,9, 1, 2011);$this->days = ($this->endTime - $this->endTime) + 1;for ($i=0; $idays; $i++) { $tmpDate = date('Y-m-d', $this->startTime + 60 * 60 * 24 * $i); $insertSql .= "('" . $tmpDate ."'),";}$insertSql = substr($insertSql,0 , strlen($insertSql)-1);$this->DB->query($insertSql);//臨時表建立完成,等於B表
SELECT tmp_currentdate AS currentdate, IF(counts IS NULL,0,counts) AS countsFROM (SELECT currentdate, counts FROM stat) AS ARIGHT JOIN tmp_table AS TMPON A.currentdate=TMP.tmp_currentdate

就能返回出

Advertisements

currentdate counts

2011-07-01 0

2011-07-02 0

2011-07-11 0

2011-07-12 15

2011-07-13 35

2011-07-14 43

Advertisements

你可能會喜歡