我想要一个查询来将一行插入到表中,我知道这很简单,但情况是该表不应超过 5 行。如果表超过五行,我需要删除旧行(或替换为新行)(基于插入时间戳)然后我需要插入一个新行。如果行数少于 5,那么我可以直接插入一行。
请分享我的查询。
这样的事情怎么样。
declare @count int
SELECT @count=COUNT(*)
from EP_ANSWERS
IF (@count<5)
// DO your insert here
ELSE
DELETE FROM TABLE
WHERE inserttimestamp = (SELECT x.inserttimestamp
FROM (SELECT MAX(t.inserttimestamp) AS inserttimestamp
FROM TABLE t) x)
// DO your insert here
如果表不可能有超过 5 行:
DELETE FROM yourtable
WHERE 5 <= (SELECT COUNT(*) FROM yourtable)
AND yourtimestamp = (SELECT MIN(yourtimestamp) FROM yourtable)
;
INSERT INTO yourtable ...
;
如果表有可能超过 5 行:
DELETE FROM yourtable
WHERE 5 <= (SELECT COUNT(*) FROM yourtable)
AND yourtimestamp NOT IN (SELECT yourtimestamp
FROM yourtable
ORDER BY yourtimestamp DESC
LIMIT 4)
;
INSERT INTO yourtable ...
;
听起来你想在表上放置一个触发器来维护这个规则,在 MySQL 中这样的东西应该可以工作
CREATE TRIGGER trg__my_table__limit_rows
BEFORE INSERT
ON my_table
FOR EACH ROW
BEGIN
IF ((SELECT COUNT(1) FROM my_table) = 5)
BEGIN
DELETE FROM my_table
WHERE id = (SELECT MIN(id) FROM my_table) -- change this to fit your logic for which record should be removed
END
END
这里的一些代码是伪代码(您没有编写架构),但我写了您需要完成自己的代码的地方。
DECLARE @NumberOfRowsToInsert INT = -- select from the data you want to insert
DECLARE @MaxNumberOfRows INT = 5
DECLARE @NumberOfExistingRows INT
DECLARE @Query VARCHAR(MAX) = 'SELECT TOP @rows id FROM SomeTable ORDER BY createdDate ASC'
SELECT @NumberOfExistingRows = COUNT(*)
FROM SomeTable
SET @Query = REPLACE(@Query,'@rows',
CAST(@NumberOfRowsToInsert - (@MaxNumberOfRows - @NumberOfExistingRows))) AS VARCHAR(1))
CREATE TABLE #IdsToDelete(id INT PRIMARY KEY)
INSERT INTO #IdsToDelete
EXEC(@Query)
DELETE FROM SomeTable
WHERE id IN (SELECT * FROM #IdsToDelete)
-- insert here..