我有一些数据表: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/

10-08 21:09
查看更多