代码之家  ›  专栏  ›  技术社区  ›  Utku Dalmaz

在特定年龄段之间选择记录

  •  0
  • Utku Dalmaz  · 技术社区  · 7 年前

    我有一个专栏( bday

    我搜索了类似的问题,发现了一个

    select * from users where datediff(year, bday, getdate()) between 18 and 22;
    

    但是,当我运行这个命令时

    #1582 - Incorrect parameter count in the call to native function 'datediff'
    

    正确的方法是什么?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    错误1582是一个MySQL错误,所以您可能正在使用MySQL。

    select u.*
    from users u
    where u.bdate >= curdate() - interval 22 year and
          u.bdate < curdate() - interval 18 year;
    

    这并不完全等同于SQL Server(或Amazon Redshift) datediff(year . . . ) 功能。更像是:

    select u.*
    from users u
    where year(u.bdate) - year(curdate()) between 18 and 22;
    

    (注意:此计算中可能存在一个off by one错误。)

        2
  •  0
  •   Mustahsan    7 年前

    根据MariaDB的文件 DATEDIFF 只接受两个参数:

    DATEDIFF(expr1,expr2) expr1 expr2 是日期或日期和时间表达式。在计算中只使用值的日期部分,然后返回( expr1 – expr2 )以从一个日期到另一个日期的天数表示的值。

    所以你的问题应该是:

    select * from users where datediff(bday,getdate()) between 18 and 22;