仅当行数超过n行时才删除值较低的行

eagi6jfj  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(268)

只有当表中有5行以上时,我才想删除值较低的行。
在本例中,我想删除id=4的行(值较低,并且有5行以上):

|--------------------|
|   id   |   value   |
|--------------------|
|    1         20    |
|--------------------|
|    2         15    |
|--------------------|
|    3         30    |
|--------------------|
|    4         5     |
|--------------------|
|    5         50    |
|--------------------|
|    6         10    |
|--------------------|

我想知道一个问题是否可行。

3phpmpom

3phpmpom1#

你可以使用 left join 在同一张table上

delete t 
from your_table t
left join 
(
  select id
  from your_table
  order by value desc
  limit 5
) tmp on t.id = tmp.id
where tmp.id is null

相关问题