(我用PostgreSQL 10标记了这个,我不知道其他数据库是否支持simmilar语法)
我有两个桌子
CREATE TABLE ids (
id SERIAL NOT NULL
);
ALTER TABLE ids ADD PRIMARY KEY (id);
CREATE TABLE ids_tab (
id INTEGER NOT NULL,
ts TIMESTAMP NOT NULL,
FOREIGN KEY(id) REFERENCES ids(id) ON DELETE CASCADE
);
我想编写delete语句来删除id(和ids_tab)中的所有记录,其中id的MAX(ts)早于N秒。我还想使用'RETURNING'语句打印已删除记录的ID和ts
就我所知(删除早于60秒):
WITH expired AS (
SELECT * FROM (
SELECT id, MAX(ts) AS latest
FROM ids_tab
GROUP BY id
) inner_tab
WHERE inner_tab.latest < (NOW() - INTERVAL '60 SECONDS')
)
DELETE FROM ids s
USING expired
WHERE s.id IN (
SELECT
id
FROM expired
)
RETURNING *;
但是输出不是我期望的。在表上执行
sqld=> select * from ids;
id
----
3
4
(2 rows)
sqld=> select * from ids_tab;
id | ts
----+----------------------------
3 | 2018-10-22 09:45:29.66359
3 | 2018-10-22 09:45:30.633459
4 | 2018-10-22 09:45:47.755611
(3 rows)
结果显示为:
id | id | latest
----+----+----------------------------
3 | 3 | 2018-10-22 09:45:30.633459
4 | 3 | 2018-10-22 09:45:30.633459
(2 rows)
我希望它能打印出来
id | id | latest
----+----+----------------------------
3 | 3 | 2018-10-22 09:45:30.633459
4 | 4 | 2018-10-22 09:45:47.755611
(2 rows)
我尝试在'DELETE FROM'中添加某种形式的关节,但我什至无法使结构良好。