我需要使用总共四(4)个表。基本上一个从另一个拉取来从另一个拉取数据以获取前一个表数据等等。
我无法在没有超时的情况下成功运行查询。我想在SUM
VISITS
ORDER
MONTH
以及特定时间段内的总销售额
表结构
table1 (WebVisits)
ID DATE WEBNUMBER VISITS
1 2012-01-01 apw-rtr8 2
.. ... ... ..
table2 (Commodities)
ID WEBNUMBER TIER1
5791 apw-rtr8 Refrigeration
.. ... ...
table3 (Attributes)
ITEM WEB_NUM
APW-RTR-8 apw-rtr8
.. ...
table4 (SalesData)
ID ITEM QUANTITY UNIT_PRICE TRANS_DATE
31905 APW-RTR-8 1 1522.38 2012-02-05
.. ... ... ... ...
SELECT
MONTH(t1.DATE) AS MONTH,
SUM(t1.VISITS) as Visits,
t2.TIER1 as Category
FROM
table1 t1
LEFT JOIN
table2 t2 ON t1.WEBNUMBER = t2.WEBNUMBER
LEFT JOIN
table3 t3 ON t2.WEBNUMBER = t3.WEB_NUM
WHERE
t1.DATE BETWEEN '2012-01-01' AND '2012-05-31'
AND t3.TIER1 = 'Cooking Equipment '
AND EXISTS( SELECT
sum(t4.UNIT_PRICE * t4.QUANTITY) as total
FROM
table4 t4
WHERE
t4.ITEM = t3.ITEM
AND t4.TRANS_DATE BETWEEN '2012-01-01' AND '2012-05-31')
GROUP BY MONTH
ORDER BY MONTH
基本上,类别(TIER1)将是已知的,日期范围将是已知的。我希望它在上面的查询中吐出与此类似的结果:
MONTH Visits Total Category
1 4054 32058.08 Cooking Equipment
2 3564 28116.17 Cooking Equipment
3 4514 25819.66 Cooking Equipment
4 3621 18732.96 Cooking Equipment
5 6521 55378.11 Cooking Equipment
答案 0 :(得分:2)
我开始编写查询并意识到我写的几乎和你写的一样。
确保存在以下indexes
:
table1.DATE
table1.WEBNUMBER
table2.WEBNUMBER
table3.WEB_NUM
table4.ITEM
table4.TRANS_DATE
编辑:
试试这个:
SELECT
MONTH(table1.DATE) AS MONTH,
SUM(table1.VISITS) as Visits,
table2.TIER1 as Category,
SUM(table4.UNIT_PRICE * table4.QUANTITY)
FROM table1
LEFT JOIN table2 USING(WEBNUMBER)
LEFT JOIN table3 table1.WEBNUMBER = table3.WEB_NUM
LEFT JOIN table4 table1.WEBNUMBER = table4.ITEM
WHERE table2.TIER1 = 'Cooking Equipment'
AND table4.TRANS_DATE BETWEEN '2012-01-01'
AND '2012-05-31'
GROUP BY MONTH
ORDER BY MONTH