如何比较日期(年,月)和日期(日,月,年)

时间:2016-05-19 02:03:13

标签: mysql sql

我有一个sql命令,我想检查日期(年,月)是否在日期(日,月,年)和日期(日,月,年)之间。以下是我的SQL命令:

SELECT *
FROM paytran
WHERE
    (StaffID BETWEEN '01' AND '01')
    AND STR_TO_DATE('01/04/2016', '%d/%m/%Y') BETWEEN STR_TO_DATE(DateFrom, '%d/%m/%Y') AND STR_TO_DATE(DateTo, '%d/%m/%Y')
    AND SubGroup = '1'
    AND Week1 = '1'
    AND PaymentMonth = STR_TO_DATE('2016/04', '%Y%m') BETWEEN STR_TO_DATE('01/03/2016', '%d/%m/%Y') AND STR_TO_DATE('31/12/2016', '%d/%m/%Y')
    AND FO = 'F'

MySQL没有错误,但结果不应为空。

2 个答案:

答案 0 :(得分:2)

SELECT * FROM TABLE_NAME
WHERE DATE_FORMAT(date, "%Y-%m") BETWEEN '2013-01' AND '2014-12';

https://stackoverflow.com/a/17541196/3155780

答案 1 :(得分:0)

嗯,这个版本看起来更简单:

SELECT *
FROM paytran
WHERE StaffID LIKE '01%' AND
      '2016-04-01' BETWEEN DateFrom AND DateTo AND
       SubGroup = '1' AND
       Week1 = '1' AND
       DATE_FORMAT(PaymentMonth, '%Y%m') BETWEEN '201604' and '201612' AND
       FO = 'F';

通常,您不需要将日期转换为字符串进行比较。如果需要日期,则会自动转换格式为YYYY-MM-DD的字符串。