簡體   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