sql >> データベース >  >> RDS >> Mysql

MySQL:特定の日付より前の最新の日付のレコードを選択する方法

    NOT EXISTSを追加できます クエリへ:

    SELECT t1.*
    FROM user_status t1
    WHERE t1.date_assigned = (SELECT MIN(t2.date_assigned)       -- the first occurance
                              FROM  user_status t2
                              WHERE t2.user_id =  t1.user_id     -- for this user
                              AND t2.status_id <> 1              -- where status not active
                              AND t2.date_assigned BETWEEN       -- within 1 yr of given date
                                   '2015-05-01' + INTERVAL 1 DAY -- (not including that date)
                              AND 
                                   '2015-05-01' + INTERVAL 1 YEAR 
                              )
          AND NOT EXISTS (SELECT 1                         -- such a record should not exist
                          FROM user_status t3
                          WHERE t3.user_id =  t1.user_id   -- for this user
                                 AND t3.status_id <> 1     -- where status is not active
                                 AND t3.date_assigned <    -- before the examined period
                                   '2015-05-01' + INTERVAL 1 DAY )
    

    デモはこちら

    編集:

    複数のアクティベーション日がある場合も考慮した次のクエリを使用できます。

    SELECT *
    FROM user_status
    WHERE (user_id, date_assigned) IN (
      -- get last de-activation date   
      SELECT t1.user_id, MAX(t1.date_assigned)
      FROM user_status AS t1
      JOIN (
        -- get last activation date 
        SELECT user_id, MAX(date_assigned) AS activation_date
        FROM user_status 
        WHERE status_id = 1
        GROUP BY user_id
      ) AS t2 ON t1.user_id = t2.user_id AND t1.date_assigned > t2.activation_date
      GROUP BY user_id
      HAVING MAX(date_assigned) BETWEEN '2015-05-01' + INTERVAL 1 DAY AND '2015-05-01' + INTERVAL 1 YEAR AND
             MIN(date_assigned) > '2015-05-01' + INTERVAL 1 DAY)
    


    1. 1つのクエリで複数のテーブルに挿入

    2. 次の値の関数エラー

    3. phpMyAdminが#2002をスローしていますmysqlサーバーにログインできませんphpmyadmin

    4. MySQLテーブルからすべての行を削除し、IDをゼロにリセットします