我一直在寫MySQL查詢很長一段時間,但我完全感覺像一個新手當談到這一點,我似乎無法弄清楚如何簡化這個查詢。基本上我只是試圖從我們的數據庫中產生一個逗號分隔的收入清單,最終被插入谷歌圖表。我必須爲「過去31天」做一個,所以我有點擰,除非我想出如何簡化這個。在我的表MySQL簡化查詢?
我的數據庫列...
- 時間:當訂單進來INT()(UNIX時間戳格式)
- 價格:訂單多少是十進制( 10,2)
SELECT
CONCAT(
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (6 * 86400)) AND time > (UNIX_TIMESTAMP() - (7 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (5 * 86400)) AND time > (UNIX_TIMESTAMP() - (6 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (4 * 86400)) AND time > (UNIX_TIMESTAMP() - (5 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (3 * 86400)) AND time > (UNIX_TIMESTAMP() - (4 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (2 * 86400)) AND time > (UNIX_TIMESTAMP() - (3 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - 86400) AND time > (UNIX_TIMESTAMP() - (2* 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time > (UNIX_TIMESTAMP() - 86400))
) as chart_rev
FROM orders_basic
LIMIT 0,1
如果可能的話,我需要它以24個小時爲單位這樣。
一如既往,任何幫助,非常感謝。謝謝!
SOLUTION
請注意:你的結果仔細一看,他們可能有,只是在錯誤的順序,如果是這樣,扭轉你的排序。
SELECT GROUP_CONCAT(total_sum) AS sum_list FROM
(
SELECT
FLOOR((UNIX_TIMESTAMP() - time)/86400) AS date,
SUM(price) AS total_sum
FROM
orders_basic
WHERE
is_testorder < 1
AND FROM_UNIXTIME(time) > DATE_SUB(NOW(), INTERVAL 1 WEEK)
GROUP BY
date
) AS s
首先我會嘗試引入['DATE_ADD()'和'INTERVAL'(http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-添加)這是更可讀。然後,我會在月份範圍內嘗試使用['GROUP_CONCAT()'](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat)天數。 – mellamokb 2012-07-12 13:31:46
感謝您向我們展示您嘗試過的內容,但如果您向我們展示了架構和所需的輸出,則會更容易。 – 2012-07-12 13:32:02
@Marcus Adams,我解釋了模式並說出我想要的輸出是什麼。我已經更清楚地爲你格式化了它。只有2列。我想要的一個例子是:1.01,3,2,4.23 – PolishHurricane 2012-07-12 14:03:39