简体   繁体   中英

Writing a sub-query using a date clause

So basically I'm trying to write something that prints the customer's name and area code if they have made a booking within the last 6 months of the current date.

My code looks like this (it has to be a subquery, not using join)

SELECT custfirstname, custareacode
FROM Customer
WHERE customerid IN (SELECT bookingdate
                FROM Bookings
                  WHERE DateDiff(CURDATE(), bookingdate) <=180);

Yet it doesn't work, but I can get it to work using a join function, but I can't with subquery, how would I do it in a subquery without a join function?

The problem with your code is that the subquery returns column bookingdate , that you are then comparing to customerid . This won't match.

I would recommend exists and a correlated subquery. Assuming that you do have column customerid in bookings , then:

select c.custfirstname, c.custareacode
from customer c
where exists (
    select 1
    from bookings b
    where b.customerid = b.customerid 
      and b.bookingdate >= current_date - interval 6 month
)

With the right index in place, exists performs usually far better than in() over a large dataset. Here, you want an index on bookings(customerid, bookingdate) .

You need to select customerid from bookings table

SELECT custfirstname, custareacode
FROM Customer
WHERE customerid IN (SELECT customerid
                FROM Bookings
                  WHERE DateDiff(CURDATE(), bookingdate) <=180);

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