【问题标题】:Writing a sub-query using a date clause使用日期子句编写子查询
【发布时间】:2021-02-21 07:09:42
【问题描述】:

所以基本上,如果客户在当前日期的最后 6 个月内进行了预订,我会尝试写一些东西来打印客户的姓名和区号。

我的代码看起来像这样(它必须是子查询,而不是使用连接)

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

但它不起作用,但我可以使用连接函数让它工作,但我不能使用子查询,我将如何在没有连接函数的子查询中做到这一点?

【问题讨论】:

    标签: mysql sql datetime subquery date-arithmetic


    【解决方案1】:

    您的代码的问题是子查询返回列bookingdate,然后您将其与customerid 进行比较。这不匹配。

    我会推荐exists 和相关子查询。假设您在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
    )
    

    有了正确的索引,exists 在大型数据集上的表现通常远好于in()。在这里,您需要在 bookings(customerid, bookingdate) 上的索引。

    【讨论】:

      【解决方案2】:

      你需要从bookings table中选择customerid

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

      【讨论】:

        猜你喜欢
        • 2014-11-02
        • 1970-01-01
        • 2019-05-07
        • 2021-01-10
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 1970-01-01
        相关资源
        最近更新 更多