我有一個包含3個表的數據庫。如何優化此查詢?需要3分鐘才能運行
- 具有一排
2000-01-01
和2040-01-01
之間的每個日期共計14610行 - 甲
locations
表,其具有用於每一個位置總共12個行 - 具有一個A
receipts
表中id
和name
甲calendar
表id
和datetime
,以及其他幾個不相關的總共約250,000行的字段
如果沒有收據,我試圖根據位置分組的日期範圍內每天獲得receipts
的計數。
我有一個工作查詢,但它需要〜3分鐘運行:
SELECT
`locations`.`name` AS `location`,
`calendar`.`date` AS `date`,
COUNT(`receipts`.`id`) AS `count`
FROM `locations`
CROSS JOIN `calendar`
LEFT JOIN `receipts` ON `calendar`.`date` = DATE(`receipts`.`datetime`)
AND `locations`.`id` = UPPER(LEFT(`receipts`.`id`, 1)) # there is no `location_id` FK. First char of receipts id is same as location id
WHERE `calendar`.`date` >= '2017-04-01' AND `calendar`.`date` <= '2017-04-07'
GROUP BY `locations`.`id`, `calendar`.`id`
ORDER BY `locations`.`name` ASC, `calendar`.`date` ASC;
我相信它有事情做與WHERE
聲明。
我改變了WHERE
這個,而不是它運行瞬間,但它不再讓我零計數無收款:
SELECT
`locations`.`name` AS `location`,
`calendar`.`date` AS `date`,
COUNT(`receipts`.`id`) AS `count`
FROM `locations`
CROSS JOIN `calendar`
LEFT JOIN `receipts` ON `calendar`.`date` = DATE(`receipts`.`datetime`)
AND `locations`.`id` = UPPER(LEFT(`receipts`.`id`, 1)) # there is no `location_id` FK. First char of receipts id is same as location id
WHERE DATE(`receipts`.`datetime`) >= '2017-04-01' AND DATE(`receipts`.`datetime`) <= '2017-04-07'
GROUP BY `locations`.`id`, `calendar`.`id`
ORDER BY `locations`.`name` ASC, `calendar`.`date` ASC;
然後我開始與子查詢亂搞,但沒有成功:
SELECT
`locations`.`name` AS `location`,
`cal`.`date` AS `date`,
COUNT(`receipts`.`id`) AS `count`
FROM `locations`
CROSS JOIN (
SELECT `calendar`.`id`, `calendar`.`date`
FROM `calendar`
WHERE `calendar`.`date` >= '2017-04-01' AND `calendar`.`date` <= '2017-04-07'
) `cal`
LEFT JOIN `receipts` ON `cal`.`date` = DATE(`receipts`.`datetime`)
AND `locations`.`id` = UPPER(LEFT(`receipts`.`id`, 1)) # there is no `location_id` FK. First char of receipts id is same as location id
WHERE DATE(`receipts`.`datetime`) >= '2017-04-01' AND DATE(`receipts`.`datetime`) <= '2017-04-07'
GROUP BY `locations`.`id`, `cal`.`id`
ORDER BY `locations`.`name` ASC, `cal`.`date` ASC;
無論如何,我可以加快第一個查詢,因爲這是給我我想要的輸出的那個?
我認爲這裏的字符串比較是導致經濟放緩,你可以考慮增加一個外鍵? –
你有適當的索引嗎?嘗試解釋你的select語句並檢查它是否使用索引。 – money
並在問題中包含解釋的結果,所以我們可以看到。 – Shadow