table_order具有复合键(id_type,date)
SELECT "September" AS `Range`,
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_items',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_items',
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_amount',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_amount'
FROM table_order
WHERE id_type IN(1,2,3,4) AND `date` >= "2015-09-01" AND `date` <= "2015-09-30"
UNION
SELECT
"August" AS `Range`,
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_items',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_items',
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_amount',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_amount'
FROM table_order
WHERE id_type IN(1,2,3,4) AND `date` >= "2015-08-01" AND `date` <= "2015-08-31"
还有其他方法可以更快地查询吗?假设我有一个包含十亿条记录的表,可以在条件下执行长日期范围查询,例如日期&gt; =&#34; 2015-01-01&#34;和日期&lt; =&#34; 2016-01-01&#34;例如。
您可以在此处找到示例:http://sqlfiddle.com/#!9/1787e/1
答案 0 :(得分:1)
使用GROUP BY
:
SELECT date_format(`date`, '%M') AS `Range`,
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_items',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_items',
SUM(IF(id_type IN(1,2), items,0)) AS 'RedandBlue_amount',
SUM(IF(id_type IN(3,4), items,0)) AS 'YellowandGreen_amount'
FROM `order`
WHERE id_type IN(1,2,3,4) AND `date` >= "2015-08-01" AND `date` <= "2015-09-30"
group by year(`date`), month(`date`)
order by year(`date`) desc, month(`date`) desc;
http://sqlfiddle.com/#!9/d76254/2
如果你总是只持续两个月,或者保持与工会的查询。但是如果范围可以大得多,那么我建议使用修改后的范围,编写要简单得多,如果只选择表中相对较小的部分,则分组不应该是性能瓶颈。
如果将年 - 月存储在单独的列中,则GROUP BY
变体可以更快,因此不需要任何函数,并相应地修改索引。您的变体可以很好地使用索引而无需修改。
您的示例(在小提琴上)没有显示索引用法,因为表中的行太少而且查询无论如何都必须读取所有行。但是你可以添加covering index (id_type, date, items)
(只是扩展你已经拥有的那个就足够了,不需要保留较短的那个),这有助于两个版本的查询。
请检查说明:
答案 1 :(得分:0)
答案 2 :(得分:0)
您也可以尝试使用索引。在许多情况下非常有用:Mysql Indexes