mysql - 在根据特定条件格式化正确的 SQL 查询时需要帮助
问题描述
这是我当前的表sandbox
:
| id | parent_id | title | text |
|----|-----------|-------|------|
| 1 | 11 | some | text |
| 2 | 11 | some | text |
| 3 | 11 | some | text |
| 4 | 11 | some | text |
| 5 | 11 | some | text |
| 6 | 14 | some | text |
| 7 | 14 | some | text |
| 8 | 19 | some | text |
| 9 | 19 | some | text |
我想要实现的是根据特定的 parent_id 保留 N 个最近的行,同时保留具有不同 parent_id 的其他行。
例如,最近 3 个 parent_id = 11 的表应如下所示:
| id | parent_id | title | text |
|----|-----------|-------|------|
| 3 | 11 | some | text |
| 4 | 11 | some | text |
| 5 | 11 | some | text |
| 6 | 14 | some | text |
| 7 | 14 | some | text |
| 8 | 19 | some | text |
| 9 | 19 | some | text |
我已经尝试过了:
DELETE FROM `sandbox`
WHERE id <= (
SELECT id
FROM (
SELECT id
FROM `sandbox`
WHERE parent_id = 11
ORDER BY id DESC
LIMIT 1 OFFSET 3 <-- keep this many records
) foo
)
但后来我松开了其他行,得到这样的表格:
| id | parent_id | title | text |
|----|-----------|-------|------|
| 3 | 11 | some | text |
| 4 | 11 | some | text |
| 5 | 11 | some | text |
任何有关正确 SQL 查询的帮助将不胜感激:)
解决方案
包含parent_id = 11
在 WHERE 子句中并使用 NOT IN 以避免删除 3 个最近的行:
DELETE FROM `sandbox`
WHERE parent_id = 11
AND id NOT IN (
SELECT id
FROM (
SELECT id
FROM `sandbox`
WHERE parent_id = 11
ORDER BY id DESC
LIMIT 3
) foo
)
推荐阅读
- reactjs - 在博览会上的“npm runeject”之后无法运行 react-native 应用程序
- tensorflow - 模块“张量流”没有属性“运行”
- laravel - 在 laravel 中不仅存储 1 个文件
- microsoft-edge - 为什么打开 Microsoft Edge 开发工具会重新加载当前页面?
- ios - Waze “分享 ETA” 深层链接
- javascript - 使用角度 6 有条件地显示和隐藏按钮
- mysql - 发现很难做sql查询
- c++ - 基于不同枚举类值联合的模板化工厂
- wordpress - 嵌入变量作为 html 链接的主题
- c# - 对动态集合中具有空值的列进行排序时引发 ArgumentException