简体   繁体   中英

Select all customers but not from current month

How can i get all customers, but not records that have signed up in CURRENT month? I thought this would work, but nope - what to do?

SELECT * FROM customers WHERE deleted = 0 AND (MONTH(created) != MONTH(NOW() AND YEAR(created) != YEAR(NOW())))
SELECT * FROM customers 
   WHERE (deleted = 0) AND  not (
         (MONTH(created) = MONTH(NOW()) AND 
         (YEAR(created) = YEAR(NOW()))

As a basic rule you should avoid calculatons on columns, they result in more CPU usage and can't use indexes.

A Standard SQL compliant solution (which also works in MySQL) simply finds the last day of the previous month:

SELECT * FROM customers 
WHERE deleted = 0
  AND created <= CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)

The MONTH(NOW() should have a closing bracket ie :- MONTH(NOW())

MONTH(created) != MONTH(NOW()) will filter out the customers whose created date's month is not equal to current month and YEAR(created) = YEAR(NOW()) will filter out the current Year

SELECT * FROM customers 
WHERE deleted = 0 
and MONTH(created) != MONTH(NOW()) 
and YEAR(created) = YEAR(NOW())

Try this

 SELECT * FROM customers  WHERE deleted = 0 AND  not (
             (MONTH(created) = MONTH(NOW()) AND 
             (YEAR(created) = YEAR(NOW()))

OR

 SELECT * FROM customers  WHERE deleted = 0 AND  !(
             (MONTH(created) = MONTH(NOW()) AND 
             (YEAR(created) = YEAR(NOW()))

You should change AND to OR :

select 
    * 
from 
    customers 
where 
    deleted = 0 
    and 
    (
        year(created) != year(now()) or month(created) != month(now())

    );

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