选择月中日期介于30到15之间的所有记录

时间:2014-11-07 08:12:45

标签: php mysql sql

我有一个名为负债的表格,其中包含以下列 loan_name,institution_name,starting_date,emi,closing_date starting_dateclosing_date的类型是varchar。

我正在尝试编写一个查询来获取数据(EMI提醒),其中starting_date的日期在30到15之间。

示例: - 我编写了以下查询,它适用于今天的日期为 07-11-2014 的情况。以下查询将返回接下来的15天的数据,但如果日期为 30-11-2014 ,那么将不会返回 未来15天。请检查以下查询。

SELECT
    user_id,
    owner_name as client_name,
    loan_name as scheme_name,
    institution_name as institution_name,
    starting_date as date_of_deduction,
    emi as amount,
    closing_date,
    "Liabilities" as instrument
FROM (`liability`)
WHERE `user_id` = '46'
AND
    (STR_TO_DATE(starting_date, "%d") between STR_TO_DATE("30-11-2014", "%d")
    and STR_TO_DATE("15-12-2014", "%d"))
AND
    (STR_TO_DATE(closing_date, "%d-%m-%Y") >= STR_TO_DATE("30-11-2014", "%d-%m-%Y"))

因为我想向客户发送电子邮件,所以我希望每月30日至15日之间有记录。我有3条记录供参考

1) starting date :- 17-09-2012 
2) starting date :- 06-10-2010 
3) starting date :- 21-08-2014

我希望查询返回记录2,即06-10-2010 ,因为每个月的日期是在30日到15日之间。

2 个答案:

答案 0 :(得分:2)

由于starting_date字段是varchar,并且您以dd-mm-yyyy格式存储日期,因此您需要使用STR_TO_DATE() functionstarting_date转换为日期时间,如下所示

STR_TO_DATE(starting_date, "%d-%m-%Y")

然后使用DAYOFMONTH() function

检查上述值的日期是否为30或更高,或15或更低
DAYOFMONTH(STR_TO_DATE(starting_date, "%d-%m-%Y")) >= 30 
    OR DAYOFMONTH(STR_TO_DATE(starting_date, "%d-%m-%Y")) <= 15

以下查询应返回正确的记录

SELECT
    user_id,
    owner_name as client_name,
    loan_name as scheme_name,
    institution_name as institution_name,
    starting_date as date_of_deduction,
    emi as amount,
    closing_date,
    "Liabilities" as instrument
FROM (`liability`)
WHERE `user_id` = '46'
AND
    (DAYOFMONTH(STR_TO_DATE(starting_date, "%d-%m-%Y")) >= 30 
    OR DAYOFMONTH(STR_TO_DATE(starting_date, "%d-%m-%Y")) <= 15)

答案 1 :(得分:0)

试试这个:

SELECT
    user_id,
    owner_name        as client_name,
    loan_name         as scheme_name,
    institution_name  as institution_name,
    starting_date     as date_of_deduction,
    emi as amount,
    closing_date,
    "Liabilities" as instrument
FROM
    (liability)
WHERE
    user_id = '46'
AND TO_DAYS(STR_TO_DATE(starting_date, "%d-%m-%Y")) >  TO_DAYS(STR_TO_DATE("30-11-2014", "%d-%m-%Y"))
AND TO_DAYS(STR_TO_DATE(starting_date, "%d-%m-%Y")) <  TO_DAYS(STR_TO_DATE("15-12-2014", "%d-%m-%Y"))
AND TO_DAYS(STR_TO_DATE(closing_date,  "%d-%m-%Y")) >= TO_DAYS(STR_TO_DATE("30-11-2014", "%d-%m-%Y"))