sql - SQL:删除两行并在表中插入新行
问题描述
我想将行对(name="aaa" 的行首先出现,name="bbb" 的行稍后出现,两行具有相同的 id)替换为具有相同 id 但 name="ccc" 的新行。
原表:
timestamp(primary key) id name
2020-02-20... 1 aaa
2020-02-20... 1 aaa -----> first row
2020-02-20... 1 ddd
2020-02-20... 1 bbb -----> second row
2020-02-20... 2 aaa
2020-02-20... 2 ccc
2020-02-20... 2 ddd
新表:
timestamp(primary key) id name
2020-02-20... 1 aaa
2020-02-20... 1 aaa
2020-02-20... 1 ccc -----> replaced by this row
2020-02-20... 1 ddd
2020-02-20... 2 aaa
2020-02-20... 2 ccc
2020-02-20... 2 ddd
时间戳是主键并且它正在增加。
是否有可能在 PostgresSQL 中实现这一点?
解决方案
如果我理解正确,这应该做你想要的:
(select id, name
from t
where name not in ('aaa', 'bbb') or
name = 'aaa' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'bbb') or
name = 'bbb' and not exists (select 1 from t t2 where t2.id = t.id and t2.name = 'aaa')
) union all
(select id, 'ccc'
from t
where name in ('aaa', 'bbb')
group by id
having count(*) = 2
)
推荐阅读
- firebase - 如何使 Flutter firebase Timestamp 仅显示日期
- python - Numpy meshgrid 2d-array
- ruby - Ruby祖先方法问题
- php - 反序列化和序列化mysql中的数据
- java - Ajax 数组对表单控制 div 的响应
- javascript - linux discord.js 没有使用 fs discord.js 设置命令
- c# - CsvHelper 未按预期写入文件
- bash - Bash:点命令双重麻烦
- amazon-web-services - 从 AWS Firehouse 到 S3 的数据安全性
- npm-install - lerna add : 在哪里找不到包
可以添加