I am fetching data from two tables, members and fees .I would like to select only those members who have not made any deposit this month. This is what I have tried but the results are not what I am intending to get . any help will be appreciated . I am using mysql .
SELECT
members.memberid,
members.companyid,
members.name,
members.initials,
members.surname,
members.datejoined,
members.usercode,
members.address,
members.cell,
members.pic,
members.idnumber, members.rank,
members.address2,
fees.feestype,fees.amountpaid,
fees.companyid,fees.paiddate,
fees.usercode
FROM
members
INNER JOIN fees
ON members.memberid = fees.memberid
WHERE
MONTH(fees.paiddate) < MONTH(CURDATE())
AND YEAR(fees.paiddate) < YEAR(CURDATE())
Best Answer
You need to do it in a diffent way: choose all members that are not
IN
the set of members who paid something this month:dbfiddle here
You actual query specified members who paid something in the years previous to the current one, and month previous to the current one.
As a second alternative, you can use
NOT EXISTS
:dbfiddle here
And yet another (not so clear, in my opinion) alternative, do a
LEFT JOIN
and set aWHERE
condition that will filter out the rows actually retrieving something from the right side of the JOIN (i.e.: using only the rowsWHERE
all columns, and specificallymemberid
are NULL on the right side):Check Best practice between using LEFT JOIN or NOT EXISTS
And check all dbfiddle here
This is called, in relational algebra, an antijoin
UPDATE
Taking a step further from Kondybas's solution, and as pointed out in the comments to Kondibas answer by ypercube, this can be further simplified to:
Writing the condition like this (i.e.: not having a function applied to paiddate), it will use an index such as:
... as can be seen on the execution plan:
dbfiddle here