简体   繁体   中英

Changing sql query to allow variable to set date span of query results

I have previously had great help from user JW on stackoverflow with an SQL query i needed to resolve. However, the requirements have changed somewhat since his original answer.

Instead of the query looking for results that fall within the last 30 days, i now need to give the admin user in the website back end the option of selecting the number of days the report needs to cover, so 30 days could be any given number now.

I have a php script and text entry where the user can enter the number of days required and it calculates the date going back x number of days. This date is then stored in a variable. We use the same method on other reports and it works very well.

The original query as worked out by JW was:

SELECT  c.customers_id
FROM    customers c 
INNER JOIN customers_info ci
ON c.customers_id = ci.customers_info_id 
LEFT JOIN codes_redeem_history pc 
ON c.customers_id = pc.customer_id
WHERE   pc.customer_id IS NULL
GROUP   BY c.customers_email_address 
HAVING  MAX(ci.customers_info_date_of_last_logon) <= subdate(now(),INTERVAL 30 DAY)

I now need to use something along the lines of:

WHERE ci.customers_info_date_of_last_logon >= '" . $ndate . "'

I cant just put that in place of the HAVING MAX section as it creates an sql syntax error

I did try:

WHERE   pc.customer_id IS NULL
AND WHERE ci.customers_info_date_of_last_logon >= '" . $ndate . "'
GROUP   BY c.customers_email_address 

But it didn't work. For information, if i select a10 day report, $ndate would be '20130301'

Thanks, Steve

Wow,

I must have had my stupid head on... The answer is so obvious to me now.

WHERE   pc.customer_id IS NULL
AND ci.customers_info_date_of_last_logon >= '" . $ndate . "'
GROUP   BY c.customers_email_address 

Can't use AND WHERE can we!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM