从两个日期之间获取数据

时间:2015-10-29 17:33:35

标签: mysql

我有这两个表

EXPENSES Table

EXPENSENAME

第一个是费用表,第二个是费用名称

Exp_Type(第一个表)是费用名称(第二个表),因为2是Food

我正在尝试根据费用类型对费用进行分组,并在某些日期之间获取数据。

这是我尝试过的,但它无法正常工作。

select
(select 
(select name from EXPENSENAME where id=EXP_TYPE)as ExpenseType,
sum(PRICE) as cost
from EXPENSES WHERE USERID=1  GROUP BY EXPENSES.EXP_TYPE),
[date]
from EXPENSES where [date] BETWEEN '10-09-2015' and '10-18-2015 23:59:59'

And

select 
(select name from EXPENSENAME where id=EXP_TYPE)as ExpenseType,
sum(PRICE) as cost,
date
from EXPENSES WHERE USERID=1 and DATE BETWEEN '01/10/2015' and '29/10/2015' GROUP BY EXPENSES.EXP_TYPE

没有日期,我通过此查询得到结果,但我需要在某些日期之间使用相同的数据,请帮助

select 
(select name from EXPENSENAME where id=EXP_TYPE)as ExpenseType,
sum(PRICE) as cost
from EXPENSES WHERE USERID=1  GROUP BY EXPENSES.EXP_TYPE

enter image description here

1 个答案:

答案 0 :(得分:1)

你想要一起加入表格

SELECT en.name as ExpenseType, SUM(e.price) as cost
FROM expenses e
JOIN expensename en ON en.id = e.exp_type
WHERE e.date BETWEEN '10-09-2015' and '10-18-2015'
GROUP BY en.name

这应该给你每个名字的费用

你当前的查询是可怕的...这就是为什么

SELECT (SELECT ... FROM ... WHERE ... ) as ...

这是创建一个相关子查询,它对父选择的每一行执行一次。意思是如果你有一个包含4行的表(SELECT ... FROM ... WHERE ... )将执行4次扫描16行(假设它来自同一个表),这通常是一种非常糟糕的获取数据的方法...如果你有一个百万行...好好做数学,这是一个坏主意