Mysql Sql:在STR\u到\u日期范围内选择
我的sql只适用于一个日期,现在我想按范围选择,我可以如何添加范围日期Mysql Sql:在STR\u到\u日期范围内选择,mysql,sql,Mysql,Sql,我的sql只适用于一个日期,现在我想按范围选择,我可以如何添加范围日期 SELECT products.id, products.name, (select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) = STR_TO_DATE('15,4,2020','%d,%m,%Y') ) as stock_
SELECT
products.id,
products.name,
(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) = STR_TO_DATE('15,4,2020','%d,%m,%Y') ) as stock_in_today,
(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and DATE(loadings.created_at) = STR_TO_DATE('15,4,2020','%d,%m,%Y') ) as total_loadings_today,
(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id) as total_stock_till_date,
(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id) as total_loadings_till_date,
((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) < STR_TO_DATE('15,4,2020','%d,%m,%Y'))-(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and DATE(loadings.created_at) < STR_TO_DATE('15,4,2020','%d,%m,%Y'))) as opening_balance,
((select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and DATE(stocks.created_at) <= STR_TO_DATE('15,4,2020','%d,%m,%Y'))-(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and DATE(loadings.created_at) <= STR_TO_DATE('15,4,2020','%d,%m,%Y'))) as closing_balance
from products
我的看法
您可以使用相关子查询。以下是一个例子:
select d.dte,
p.id, p.name,
(select coalesce(sum(s.qty), 0)
from stocks s
where s.pid = p.id and
s.created_at >= d.dte and
s.created_at < d.dte + interval 1 day
) as stock_in_today,
. . .
from products p cross join
(select date('2020-01-01') as dte union all
select date('2020-02-01')
) d
对于其余的子查询,依此类推
请注意我对查询所做的更改:
添加了表别名,因此表引用更易于写入和读取。
对日期文本使用标准日期格式。
将日期逻辑更改为使用直接比较而不是函数。
此查询可以使用stockpid上的索引,该索引创建于。@EmmaMfinanga。只有在d派生表中有重复项时,结果才会相乘。我没有重复的id