繁体   English   中英

MySQL计算两个日期之间的差异,但有一个扭曲

[英]MySQL Calculating The Difference Between two dates but with a twist

我有2个表: ProductUser

Product:
    Date(Datetime)
    Phone_Number(Number).

User: 
    Date (Datetime)
    Phone_Number(Number)
    Type(Value of N or C).

将新用户添加到User表时,会为其指定日期,电话号码和值“N”(N为新)。 当用户被取消时,会给它一个日期,电话号码和值“C”(C表示已取消)。

使用MySQL,我需要找出创建用户的日期和用户被取消的日期之间的日期差异,以及他们是否有一个产品(可以通过电话号码将用户与产品匹配)在创建日期和取消日期。

任何帮助将不胜感激,因为我的查询写作并不可怕,但我无法解决这个问题。

谢谢。

SELECT
    /* Anything you want from the User table */
    /* CASE statement that checks if prod.phone_number is not null which means a product was present */
FROM
    User user_new
    JOIN User user_can
    ON user_new.phone_number = user_can.phone_number
    LEFT JOIN Product prod
    ON prod.phone_number = user_new.phone_number
WHERE
    (prod.Date IS NULL) OR -- Either there was no record.
    (prod.Date BETWEEN user_new.Date AND user_can.Date) -- or a product existed between the two dates.

您需要首先自行加入User表以查找创建和取消的日期。 然后加入Product表以查看是否有任何内容。

SELECT u.Phone_Number, u.Created, u.Cancelled, p.Date as 'ProductDate'
FROM (
    SELECT u1.Phone_Number, u1.Date as 'Created', u2.Date as 'Cancelled'
    FROM User u1
      JOIN User u2 on u1.Phone_Number=u2.Phone_Number
    WHERE u1.Type = 'N'
      and u2.Type = 'C'
  ) u
  LEFT JOIN Product p on u.Phone_Number = p.Phone_Number
                     and p.Date between u.Created and u.Cancelled

如果您只存储一个日期字段,那么您的表格将无法确定用户创建和取消日期之间的差异。 但是,如果您有2列,user.createdDate和user.cancelledDate,您可以使用SELECT DATEDIFF(user.createdDate,user.cancelledDated)AS DiffDate我不知道DATEDIFF是否适用于datetime对象,我已将它用于普通日期格式化为“year-mm-dd”,它将为您提供带有DiffDate的查询结果对象,DiffDate是天数的整数。 如果user.cancelledDate在user.createdDate之前,您将得到一个负整数。

暂无
暂无

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

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