Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用长日期范围条件提高mysql查询速度_Mysql - Fatal编程技术网

使用长日期范围条件提高mysql查询速度

使用长日期范围条件提高mysql查询速度,mysql,Mysql,我有两张桌子:桌车和桌订单: 我想要一张这样的桌子: 表顺序具有复合键(id类型、日期) 选择“九月”作为“范围”, 总和(如果(id_键入(1,2),项,0))为“红色和蓝色_项”, 总和(如果(id_键入(3,4),项,0))为“黄色和绿色_项”, 金额(如果(id_键入(1,2),项目,0))为“红色和蓝色金额”, 金额(如果(id_键入(3,4),项目,0))为“黄色和绿色金额” 从表中按顺序排列 其中id_输入(1,2,3,4)和'date`>=“2015-09-01”和'date

我有两张桌子:桌车和桌订单:

我想要一张这样的桌子:

表顺序具有复合键(id类型、日期)

选择“九月”作为“范围”,
总和(如果(id_键入(1,2),项,0))为“红色和蓝色_项”,
总和(如果(id_键入(3,4),项,0))为“黄色和绿色_项”,
金额(如果(id_键入(1,2),项目,0))为“红色和蓝色金额”,
金额(如果(id_键入(3,4),项目,0))为“黄色和绿色金额”
从表中按顺序排列
其中id_输入(1,2,3,4)和'date`>=“2015-09-01”和'date`=“2015-08-01”以及'date`=“2015-01-01”和date1)您的示例显示了金额的
sum(items)
,我认为这是一个复制错误

2) 您可能正在寻找的是
组\u CONCAT


您也可以尝试使用索引。在许多情况下非常有用:

使用
分组方式:

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;
选择日期格式(`date`,'%M')作为`Range`,
总和(如果(id_键入(1,2),项,0))为“红色和蓝色_项”,
总和(如果(id_键入(3,4),项,0))为“黄色和绿色_项”,
金额(如果(id_键入(1,2),项目,0))为“红色和蓝色金额”,
金额(如果(id_键入(3,4),项目,0))为“黄色和绿色金额”
从`命令`

其中id_输入(1,2,3,4)和'date`>=“2015-08-01”和'date`当然可以,请将其反规范化。您能解释更多吗?日期的数据类型是什么datetime@Drew:是的,必须是日期时间。但是如果你有更好的建议的话?我在这个表中使用了索引:(id\u type,date),所以你不能从中得到更多。好的:D我希望你会有更多的优化想法;)伟大的它对月或年数据很有用。这就是我所需要的,但还有一个问题:有时我想使用这样的条件:
date
>=“2015-08-15”和
date
@sontd如果你只想从该范围中选择一个组,而不是两个,那么你是对的,这个简单的分组不会成功。您可以创建一个可以工作的表达式或使用原始解决方案。
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;