简体   繁体   English

使用日期子句编写子查询

[英]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.所以基本上我想写一些东西来打印客户的姓名和区号,如果他们在当前日期的最后 6 个月内进行了预订。

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 .您的代码的问题在于子查询返回列bookingdate ,然后您将其与customerid进行比较。 This won't match.这不会匹配。

I would recommend exists and a correlated subquery.我会推荐exists和相关的子查询。 Assuming that you do have column customerid in bookings , then:假设您在bookings有列customerid ,那么:

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.有了正确的索引,在大型数据集上, exists性能通常比in()好得多。 Here, you want an index on bookings(customerid, bookingdate) .在这里,您需要一个关于bookings(customerid, bookingdate)的索引。

You need to select customerid from bookings table您需要从bookings table选择customerid

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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