I’ve got the following query:
$data = mysql_fetch_array(mysql_query("SELECT
c.`id` AS cid,
p.`id` AS pid,p.`email`
FROM `coupons` AS c
LEFT JOIN `coupons_partners` AS cp ON cp.`cid` = c.`id`
LEFT JOIN `partners` AS p ON p.`id` = cp.`pid`
LEFT JOIN `bills` AS b ON b.`pid` = p.`id`
WHERE
(
CURRENT_DATE() BETWEEN c.`expires` AND ADDDATE(c.`expires`, INTERVAL 1 MONTH)
)
OR
(
CURRENT_DATE() NOT BETWEEN c.`expires` AND ADDDATE(c.`expires`, INTERVAL 1 MONTH)
AND
CURRENT_DATE() BETWEEN b.`date` AND ADDDATE(b.`date`, INTERVAL 1 MONTH)
)
ORDER BY b.`id` DESC"));
It’s kinda messy. I want to do a cronjob and create bills automatically. They should only be created after 1 month a coupon expires (c.expires is DATETIME) or if the LAST bill (b.date) was created 1 month ago.
The thing also is that I don’t want to create any bill if the coupon didn’t started yet. And this is possible, because I create coupons that’ll start in maybe 3 months. So I guess the “Between-Solution” doesn’t fit here?
I’m trying to figure it out to do it properly, but now I would appreciate any help.
I would be happy and thankful, if someone could help me out.
Best Regards,
Alex
Use DATEDIFF
yields 1 since 02-10 is one month after 01-10
month can be changed to day to get the number of days instead.
Reference: http://www.1keydata.com/sql/sql-datediff.html
UPDATE:
In MSQL you could use DATEDIFF because it can be passed month as an argument, the MySQL version only returns days. In MySQL you could instead use PERIOD_DIFF. Although it doesn’t know about the exact number of days in each month.
“Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values.”
If you need to know if exactly how many months differ you need to make a multistep calculation. To find out the number of days in a month you could use the LAST_DAY function and from the results extract the day part and use as the basis for further calculations.