MySQL:如果行不存在,则返回0

4

我已经苦思冥想了一段时间,现在来这里求助 :) 我是SQL初学者,所以也许对你们来说很简单...

我有这个查询:

SELECT COUNT(*) AS counter, recur,subscribe_date  
FROM paypal_subscriptions  
WHERE recur='monthly' and subscribe_date > "2010-07-16" and subscribe_date < "2010-07-23"  
GROUP BY subscribe_date  
ORDER BY subscribe_date  

现在我展示的日期是硬编码的,我的应用程序将提供一个可变的日期范围。

目前,我正在获得一个结果表格,在该表格中存在该日期的值。

counter |recur | subscribe_date   
2    |    Monthly | 2010-07-18  
3    |    Monthly | 2010-07-19  
4    |    Monthly | 2010-07-20    
6    |    Monthly | 2010-07-22

我希望返回柜台列的值,如果日期不存在。
counter |recur | subscribe_date   
0    |    Monthly | 2010-07-16  
0    |    Monthly | 2010-07-17  
2    |    Monthly | 2010-07-18  
3    |    Monthly | 2010-07-19  
4    |    Monthly | 2010-07-20    
0    |    Monthly | 2010-07-21  
6    |    Monthly | 2010-07-22  
0    |    Monthly | 2010-07-23 

这是可能的吗?

2
这并不像你想象的那样简单,但看看解答:https://dev59.com/WkbRa4cB1Zd3GeqPwgYt#373734是同一个问题。 - Haim Evgi
3个回答

0
你需要一个日期表来进行分组。在MSSQL中使用类似this的CTE非常容易 - 我不确定MySQL是否有类似的东西? 否则,您将需要创建一个硬表作为一次性练习。
编辑:试试这个:
SELECT COUNT(pp.subscribe_date) AS counter, dl.date, MIN(pp.recur)
FROM date_lookup dl 
    LEFT OUTER JOIN paypal pp 
    on (pp.subscribe_date = dl.date AND pp.recur ='monthly') 
WHERE dl.date >= '2010-07-16' and dl.date <= '2010-07-23'
GROUP BY dl.date
ORDER BY dl.date
  • 查询的主题需要更改为date_lookup表(左外连接的顺序变得重要)
  • Count(*)不起作用,因为“日期”记录始终存在-需要计算PayPay表中的某些内容
  • pp.recur ='monthly'现在是一个连接条件,而不是LOJ的过滤器

最后,在选择列表中显示pp.recur不起作用。

我使用了聚合函数,但如果没有PayPal记录,则MIN(pp.recur)将返回null

当您参数化查询时,可以做的是重复Recur Type Filter?再次抱歉MSSQL语法

SELECT COUNT(pp.subscribe_date) AS counter, dl.date, @ppRecur
FROM date_lookup dl 
    LEFT OUTER JOIN paypal pp 
    on (pp.subscribe_date = dl.date AND pp.recur =@ppRecur) 
WHERE dl.date >= @DateFrom and dl.date <= @DateTo
GROUP BY dl.date
ORDER BY dl.date

好的,我采纳了你的建议并创建了一个date_lookup表。它只有一列,里面包含了每年的每一天。这是我的新查询:SELECT COUNT(*) AS counter, pp.recur, dl.date
FROM paypal pp
LEFT OUTER JOIN date_lookup dl on (pp.subscribe_date = dl.date)
WHERE pp.recur='monthly' and pp.subscribe_date > "2010-07-16"
and pp.subscribe_date < "2010-07-23"
GROUP BY pp.subscribe_date
ORDER BY pp.subscribe_date 但我仍然得到相同的结果 :(
- Loony2nz

0

由于没有简单的方法来实现这个,我不得不让应用程序为我填充空白,而不是让数据库返回我想要的数据。这确实会影响性能,但对于报告的完成是必要的。

我肯定会在不久的将来研究如何从数据库中返回我想要的内容。我会尝试非nb的解决方案。

谢谢大家!


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接