mysql - 根据年份和月份获取数据

标签 mysql sql

我有一个包含一些数据的表:month_number (int), year(int)。

我想获取2年2个月的数据

SELECT
  tt.year AS raw_annee,
  tt.month AS raw_mois,
  tt.product AS raw_produit,
  tt.quantity_product AS tonnes_prod,
  tt.quantity_n AS raw_tonnes_N,
  tt.quantity_p AS raw_tonnes_P,
  tt.quantity_k AS raw_tonnes_K
FROM test_test as tt    
  WHERE (tt.year >= 2014 AND tt.month_number >= 5)
  AND (tt.year <= 2018 AND tt.month_number <= 5)
  ORDER BY tt.year desc, tt.month_number desc;

但我只获得 2014 年至 2018 年“5 月”月份的数据,但我的想法是获取 2014 年 5 月的数据 ---> 2018 年 5 月

你能帮帮我吗?

最佳答案

您只想比较第一年和最后一年的月份:

  WHERE (tt.year > 2014 AND tt.year < 2018)
    or  (tt.year = 2014 AND tt.month_number >= 5)
    or  (tt.year = 2018 AND tt.month_number <= 5)

或者:

WHERE (tt.year * 100 + tt.month_number >= 201405)
  AND (tt.year * 100 + tt.month_number <= 201805)

或者,MySQL 不支持:

WHERE (tt.year, tt.month_number) between (2014,5) and (2018,5)

由 Raymond Nijland 改编为 MySQL:

WHERE (tt.year, tt.month_number) >= (2014,5) AND (tt.year, tt.month_number) <= (2018,5)

关于mysql - 根据年份和月份获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54651670/

相关文章:

mysql - Laravel数据库sql

php - 如何每天轮换报价

php 使用上一页中的参数选择查询

mysql - SQL:分组依据和具有子查询问题的 COUNT(*)

mysql - 使用基于动态字段的 DATE_SUB()

mysql - 切换数据库中的记录

javascript - 如何将特定的表值传递给我们从数据库表中获取的 ajax?

mysql - 能否从数据文件中查到mysql版本,需要数据恢复

php - 创建带有日期列的数据透视表的最佳方法

php - 如何从包含一组重复值(clm1、clm2、cl3)的表中选择 id?