条件MySQL查询的具体例子

Specific example of conditional MySQL query

我有一个名为 "budgets" 的 table,其中包含我们每个月在不同国家/地区的销售预算数据。

我需要创建一个条件查询,以提取给定月份每个国家/地区的预算数据。

如果尚未添加特定国家/地区的预算,则查询应return上个月的预算(它将始终存在)。

  country   | date       | budget
===================================
| Argentina | 2018-02-01 | 0
| Brazil    | 2018-02-01 | 0
| Brazil    | 2018-03-01 | 0
| Colombia  | 2018-02-01 | 0
| Chile     | 2018-02-01 | 0
| Chile     | 2018-03-01 | 

示例:

如果我们从上面的示例 table 中提取“2018-03-01”的数据,则 return 应该是:

  country   | date       | budget
===================================
| Argentina | 2018-02-01 | 0
| Brazil    | 2018-03-01 | 0
| Colombia  | 2018-02-01 | 0
| Chile     | 2018-03-01 | 

我想避免使用 'latest date' 想法(查询总是 return 每个国家/地区的最新现有日期),因为新预算可以添加到 table 在本月底之前。

我正在尝试找到一种在单个查询中完成它的方法,但如果那不可能,多个也可以。

我正在使用 PHP7 向 MariaDB 发送查询。

感谢您的贡献!

这真是一个过滤问题。您想要日期等于或早于给定日期的行:

select b.*
from budgets b
where b.date = (select max(b2.date)
                from budgets b2
                where b2.country = b.country and
                      b2.date <= '2018-03-01'
               );

在国家和月份的数据库中,性能可能不是什么大问题。但如果是,您需要 budgets(country, date).

上的索引