【问题标题】:MySql select all records from the table with month and year in the range from that month and year to all the past [closed]MySql从表中选择月份和年份的所有记录,范围从那个月份和年份到过去的所有[关闭]
【发布时间】:2021-02-03 07:41:25
【问题描述】:

我有一个包含两个字段“月”和“年”的表,我如何进行查询,通过一个月和一年,选择该月和该年的所有内容。 例如,如果查询中的月份和年份是月份为 9,年份为 2020,如果我在表中有来自同一月份和同一年或前两个月或过去一年或一年以上的记录,他们都出去了吗?

谢谢大家

【问题讨论】:

    标签: mysql sql datetime where-clause date-arithmetic


    【解决方案1】:

    一个选项使用算术:

    select *
    from mytable
    where year * 100 + month <= date_format(current_date, '%Y%m')
    

    或者:

    where year * 100 + month <= year(current_date) * 100 + month(current_date)
    

    【讨论】:

    • 条件中的年份和月份表示传递给查询的值,如示例中的 2020 和 9?
    • @Robert:好的,所以只需将year(current_date) 替换为2020 并将month(current_date) 替换为9。所以:where year * 100 + month &lt;= :p_year * 100 + :p_month,其中:p_year:p_month 是查询的参数。
    • WHERE myTable.pay = 0 AND myTable.year * 100 + myTable.month
    • 对不起,它可以工作,请你解释一下这个逻辑是如何工作的
    • 好的,我想我明白了,您实际上将由月份和年份组成的日期转换为数字,在示例中它将变为 202009,在其他日期执行相同的过程,所以让我们比较数字而不是实际日期,这意味着没有本地方法可以达到相同的结果
    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多