为每个 SID 删除除 2 行以外的所有行(降序)
Delete all rows except 2 for each SID (descending order)
我有一个 table 这种结构。每个 SID 都有不同的 ITEMID
| sid | itemid |
|---| ---------|
| 1 | 20600 |
| 1 | 20598 |
| 1 | 20597 |
| 1 | 20596 |
| 1 | 20595 |
| 1 | 20594 |
...
...
| 2 | 19600 |
| 2 | 19598 |
| 2 | 19597 |
| 2 | 19596 |
| 2 | 19595 |
| 2 | 19594 |
...
...
我需要的是删除除最后 2 行之外的所有 ITEMID 以降序方式排序的行。
这是我想要得到的结果:
| sid | itemid |
|---| ---------|
| 1 | 20600 |
| 1 | 20598 |
| 2 | 19600 |
| 2 | 19598 |
谢谢
安德里亚
在 MySQL 8+ 上,我们可以尝试使用 ROW_NUMBER
:
删除连接
DELETE t1
FROM yourTable t1
INNER JOIN
(
SELECT sid, itemid,
ROW_NUMBER() OVER (PARTITION BY sid ORDER BY itemid DESC) rn
FROM yourTable
) t2
ON t2.sid = t1.sid AND t2.itemid = t1.itemid
WHERE
t2.rn > 2;
DELETE t0
FROM test t0
JOIN ( SELECT t1.sid,
( SELECT itemid
FROM test t2
WHERE t1.sid = t2.sid
ORDER BY itemid DESC LIMIT 1,1 ) itemid
FROM ( SELECT DISTINCT t3.sid
FROM test t3 ) t1 ) t4 USING (sid)
WHERE t0.itemid < t4.itemid;
https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=c6d67da817ddbb9fb890693564bcd49c
我有一个 table 这种结构。每个 SID 都有不同的 ITEMID
| sid | itemid |
|---| ---------|
| 1 | 20600 |
| 1 | 20598 |
| 1 | 20597 |
| 1 | 20596 |
| 1 | 20595 |
| 1 | 20594 |
...
...
| 2 | 19600 |
| 2 | 19598 |
| 2 | 19597 |
| 2 | 19596 |
| 2 | 19595 |
| 2 | 19594 |
...
...
我需要的是删除除最后 2 行之外的所有 ITEMID 以降序方式排序的行。 这是我想要得到的结果:
| sid | itemid |
|---| ---------|
| 1 | 20600 |
| 1 | 20598 |
| 2 | 19600 |
| 2 | 19598 |
谢谢 安德里亚
在 MySQL 8+ 上,我们可以尝试使用 ROW_NUMBER
:
DELETE t1
FROM yourTable t1
INNER JOIN
(
SELECT sid, itemid,
ROW_NUMBER() OVER (PARTITION BY sid ORDER BY itemid DESC) rn
FROM yourTable
) t2
ON t2.sid = t1.sid AND t2.itemid = t1.itemid
WHERE
t2.rn > 2;
DELETE t0
FROM test t0
JOIN ( SELECT t1.sid,
( SELECT itemid
FROM test t2
WHERE t1.sid = t2.sid
ORDER BY itemid DESC LIMIT 1,1 ) itemid
FROM ( SELECT DISTINCT t3.sid
FROM test t3 ) t1 ) t4 USING (sid)
WHERE t0.itemid < t4.itemid;
https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=c6d67da817ddbb9fb890693564bcd49c