MySQL根据子查询设置OFFSET

时间:2016-08-30 12:31:53

标签: mysql


我试图删除所有超过一周的记录,同时为每个用户保留至少一个记录 例如:

<div class="content-block-body">
  <div class="content-block-text">
    <div>月額固定と成果報酬が選べます</div>
    <div>成果報酬額に上限おもうけられます</div>
    <div>料金が明瞭で予算に合わせた対策が可能</div>
  </div>
  <div class="content-block-image"> <img src="image-1.jpg"> </div>
</div>

应该成为

| ID | user |   date   | other columns...
|  1 | 1234 | -2 days  | ...    
|  2 | 1234 | -3 days  | ...
|  3 | 1234 | -8 days  | ...
|  4 | 5678 | -9 days  | ...
|  5 | 5678 | -10 days | ...

到目前为止,我已经做到了这一点,但它使用CASE来设置OFFSET,所以它不起作用:

| ID | user |   date   | other columns...
|  1 | 1234 | -2 days  | ...    
|  2 | 1234 | -3 days  | ...
|  4 | 5678 | -9 days  | ... // Keeping the most recent record for this user

所以问题是:如何修复上面的代码?

P.S。:除了SQL中的大多数基本操作外,我对任何事都比较新。

2 个答案:

答案 0 :(得分:2)

通过按用户分组交易,您可以确定要保留的交易:

SELECT   user, MAX(date) date
FROM     transactions
GROUP BY user

然后,您可以使用多表DELETE语法在这些结果与原始表之间建立外部联接,以便仅删除所需的记录:

DELETE transactions
FROM   transactions NATURAL LEFT JOIN (
         SELECT   user, MAX(date) date
         FROM     transactions
         GROUP BY user
       ) t
WHERE  date < CURRENT_DATE - INTERVAL 7 DAY
   AND t.date IS NULL

答案 1 :(得分:0)

DELETE FROM transactions tt WHERE tt.id NOT IN (
SELECT ID FROM transactions t WHERE
    DATE(t.date) <= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND
    t.user = tt.transactions.user 
    ORDER BY t.ID DESC limit 1
)